Python if-else使用

1.從鍵盤上輸⼊⼀個數,顯示它的絕對值(不允許使⽤abs) 。

num = float(input("請輸入一個實數:"))
if num > 0:
    print(num)
else:
    print(-num)

2.假設⽤戶名爲admin,密碼爲123abc,從控制檯分別輸⼊⽤戶名和密碼,如果和已知⽤戶名和密碼都匹配上的話,則驗證成功,否則驗證失敗。

UserName = input("請輸入用戶名:")
UserKey = input("請輸入密碼:")
if UserName=='admin' and UserKey=='123abc':
    print("驗證成功")
else:
    print("驗證失敗")

3.計算⾯積
編寫程序,由⽤戶輸⼊的三⻆形的三條邊,計算三⻆形的⾯積。
解題提示:
1)用海倫公式計算三角形面積;
2)考慮⽤戶輸⼊的三條邊是否能構成三⻆形;

import math
a = float(input("請輸入三角形的第一條邊:"))
b = float(input("請輸入三角形的第二條邊:"))
c = float(input("請輸入三角形的第三條邊:"))
if a+b > c and a+c > b and b+c > a:
    l = (a+b+c)/2
    s = math.sqrt(l*(l-a)*(l-b)*(l-c))
    print(s)
else:
    print("您輸入的三條邊不能構成三角形")

4.已知有分段函數:

從鍵盤上輸⼊x的值,輸出f(x)的值

x = float(input("請輸入x的值:"))
if x > 1:
    print("f(x)=", 3*x-5)
elif -1 <= x <= 1:
    print("f(x)=", x+2)
else:
    print("f(x)=", 5*x+3)

 

5.百分制成績轉換爲等級製成績。要求:如果輸⼊的成績在90分以上(含90分)輸出A;80分-90分(不含90分)輸出 B;
70分-80 分(不含80分)輸出C;60分-70分(不含70分)輸出D;60分以下輸出E。

grade = float(input("請輸入成績:"))
if grade >= 90:
    print("A")
elif 80 <= grade < 90:
    print("B")
elif 70 <= grade < 80:
    print("C")
elif 60 <= grade < 70:
    print("D")
else:
    print("E")

6. 任給兩個實數,判斷這兩個實數作爲座標所在的象限。
例如給2.5 -5.6 顯示在第4象限!
提示: 考慮在座標軸上和原點的情況

x = float(input("請輸入x軸座標值:"))
y = float(input("請輸入y軸座標值:"))
if x > 0 and y == 0:
    print("該點在x軸的正半軸上")
elif x > 0 and y > 0:
    print("該點在第一象限內")
elif x == 0 and y > 0:
    print("該點在y軸的正半軸上")
elif x < 0 and y > 0:
    print("該點在第二象限內")
elif x < 0 and y == 0:
    print("該點在x軸的負半軸上")
elif x < 0 and y < 0:
    print("該點在第三象限內")
elif x == 0 and y < 0:
    print("該點在y軸的負半軸上")
else:
    print("該點在第四象限內")

7.寫⼀個四則計算器,運⾏界⾯如下:
(1)不要求連續做,每次只做⼀種運算
 功能菜單:
------------------------------------------
[1] 加法 [2] 減法
[3] 乘法 [4] 除法
[0] 退出
------------------------------------------
請輸⼊您的選擇(0—4):1
請輸⼊第⼀個數:5
請輸⼊第⼆個數:3
3 + 5 = 8
print("功能菜單:")

print("------------------------------------------")
print("[1] 加法 [2] 減法\n[3] 乘法 [4] 除法\n[0] 退出")
print("------------------------------------------")
choice = int(input("請輸入你的選擇(0-4)"))
if choice == 1:
    a = float(input("請輸入第一個數:"))
    b = float(input("請輸入第二個數:"))
    print("%.2f + %.2f = %.2f" % (a, b, a+b))
elif choice == 2:
    a = float(input("請輸入第一個數:"))
    b = float(input("請輸入第二個數:"))
    print("%.2f - %.2f = %.2f" % (a, b, a - b))
elif choice == 3:
    a = float(input("請輸入第一個數:"))
    b = float(input("請輸入第二個數:"))
    print("%.2f * %.2f = %.2f" % (a, b, a * b))
elif choice == 4:
    a = float(input("請輸入第一個數:"))
    b = float(input("請輸入第二個數:"))
    print("%.2f / %.2f = %.2f" % (a, b, a / b))
elif choice == 0:
    print("退出")
else:
    exit(0)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章