python分支結構


if分支

一、單分支結構

# if 表達式:
#     語句塊
# 后續語句

# 執行流程:如果表達式結果為真,則執行語句塊。否則,直接執行后續語句

二、雙分支結構

# 雙分支語句
# if 表達式:
# 語句塊a
# else:
# 語句塊b
# 后續語句
# 執行流程:如果表達式成立,執行語句塊a,否則執行語句b

三、多分支結構


if 表達式:
語句塊1
elif 表達式:
語句塊2
elif 表達式2:
語句塊3
else:
語句塊4
后續語句


練習:

1.從鍵盤輸入一個值,求他的絕對值

a = int(input("請輸入一個數:"))
if a < 0:
print(-a)
else:
print(a)

2.假設用戶名為admin,密碼為123ABC,從控制台輸入用戶名和密碼,如果和已知用戶名和密碼匹配上的話則驗證成功,否則驗證失敗
name = input("請輸入用戶名:")
password = input("請輸入密碼:")
if name == 'admin' and password == '123abc':
print("驗證成功")
else:
print("驗證失敗")

注意判等符合是==,不是=

3.計算三角形的面積。輸入三角形的三條邊。
要判斷輸入的值能否構成三角形
a = int(input("請輸入三角形的a邊長"))
b = int(input("請輸入三角形的b邊長"))
c = int(input("請輸入三角形的c邊長"))
l = (a + b + c) / 2
if (a + b > c) or (a + c > b) or (a + c > b):
s = (l*(l-a) * l*(l-b) * l*(l-c)) ** (1/2)
print("%.0f" % s)
else:
print("不是三角形")


4.百分制成績轉換為等級制成績。要求:    如果輸⼊入的成績在90分以上(含90分)輸出A;80分-90分(不不含90分)輸出 B;70分-80 分(不不含80分)輸出C;60分-70分(不不含70分)輸出D;60分以下輸出E。
score = int(input("請輸入分數:"))
if score >=90:
print("成績為A")
elif score >= 80 and score < 90:
print("成績為B")
elif score >=70 and score < 80:
print("成績為C")
else:
print("成績為D")
5.任給兩個實數,判斷這兩個實數作為坐標所在的象限。 例例如給2.5 -5.6  顯示在第4象限! 提示: 考慮在坐標軸上和原點的情況 
a = float(input("請輸入第一個數:"))
b = float(input("請輸入第一個數:"))
if a == 0 and b == 0:
print("在原點")
elif a == 0 and b != 0:
print("在y軸")
elif a != 0 and b == 0:
print("在x軸")
elif a > 0:
if b > 0:
print("在第1限象")
else:
print("在第4限象")
elif a < 0:
if b > 0:
print("在第2限象")
else:
print("在第3限象")
6.寫⼀一個四則計算器器,運⾏行行界⾯面如下: 
(1)不不要求連續做,每次只做⼀一種運算

功能菜單: 
------------------------------------------
[1] 加法 [2] 減法 
[3] 乘法 [4] 除法 
[0] 退出 
------------------------------------------
請輸⼊入您的選擇(0—4):1
請輸⼊入第⼀一個數:5
請輸⼊入第⼆二個數:3
3 + 5 = 8


print("功能菜單:")
print("-----------------------------")
print('''
[1] 加法 [2] 減法
[3] 乘法 [4] 除法
[0] 退出''')
print("-----------------------------")
print()
choice = int(input("請輸入您的選擇(0-4):"))
if choice == 0:
exit()
else:
a = int(input("請輸入第一個數:"))
b = int(input("請輸入第一個數:"))
if choice == 1:
print("%s+%s=%s" % (a, b, a + b))
elif choice == 2:
print("%s-%s=%s" % (a, b, a - b))
elif choice == 3:
print("%s*%s=%s" % (a, b, a * b))
elif choice == 4:
print("%s/%s=%s" % (a, b, a / b))
7..已知有分段函數:

 

 

 
     從鍵盤上輸⼊入x的值,輸出f(x)的值
x = int(input("請輸入x的值:"))
if x > 1:
print(3 * x - 5)
elif x >= -1 and x <= 1:
print(x + 2)
else:
print(5 * x + 3)



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM