鹹魚的Python學習日誌03_分支結構
阿新 • • 發佈:2021-02-04
技術標籤:Python
應用場景
之前所有的語句都是順序執行的,若是碰到需要判斷進行多分支處理的情況就無能為力了。程式中為此出現了分支結構或選擇結構來處理這樣的問題。
if語句的使用
在python中,使用if、elif和else關鍵字來構造分支結構。
"""
使用者身份驗證
"""
username=input('請輸入使用者名稱:')
password=input('請輸入口令:')
if username == 'admin' and password == '123456':
print('身份驗證成功!' )
else:
print('身份驗證失敗!')
Python中使用縮排的方式來表示程式碼的層次結構這和C/C++是不一樣的。如果要執行多個語句,宇通保持相同的縮排即可。
多分支的分段函式處理
f
(
x
)
=
{
3
x
−
5
(x>1)
x
+
2
(-1
≤
x
≤
1)
5
x
+
3
(x<-1)
f(x)=\begin{cases} 3x-5&\text{(x>1)}\\x+2&\text{(-1}\leq\text{x}\leq\text{1)}\\5x+3&\text {(x<-1)}\end{cases}
f(x)=⎩⎪⎨⎪⎧3x−5x+25x+3(x>1)(-1≤x≤1)(x<-1)
"""
分段函式求值
3x - 5 (x > 1)
f(x) = x + 2 (-1 <= x <= 1)
5x + 3 (x < -1)
"""
x = float(input('x = '))
if x > 1:
y = 3*x-5
elif x >= -1 and x <= 1:
y = x+2
else:
y = 5*x + 3
print('f(%.2f)=%.2f' % (x, y))
在實現的時候也可以用巢狀的方式來進行處理。
"""
分段函式求值
3x - 5 (x > 1)
f(x) = x + 2 (-1 <= x <= 1)
5x + 3 (x < -1)
"""
x = float(input('x = '))
if x > 1:
y = 3*x-5
elif x <=1:
if x>=-1:
y=x+2
else:
y=5*x+3
print('f(%.2f)=%.2f' % (x, y))
練習
練習一
英制單位英寸與公制單位釐米互換。 1英寸 = 2.54釐米
"""
英制單位英寸與公制單位釐米互換。 1英寸 = 2.54釐米
"""
value = float(input('請輸入長度:'))
unit = input('請輸入單位')
if unit == '英寸' or unit == 'in':
print('%.2f英寸 = %.2f釐米' % (value, value*2.54))
elif unit == '釐米' or unit == 'cm':
print('%.2f釐米 = %.2f英寸' % (value, value/2.54))
else:
print('單位無效!')
練習二
百分制成績轉換為等級製成績
要求:如果輸入的成績在90分以上(含90分)輸出A;80分-90分(不含90分)輸出B;70分-80分(不含80分)輸出C;60分-70分(不含70分)輸出D;60分以下輸出E。
"""
百分制成績轉換為等級製成績
"""
score = float(input('請輸入成績'))
if score>=90:
print('A')
elif score>=80:
print('B')
elif score>=70:
print('C')
elif score>=60:
print('D')
else:
print('E')
練習三
輸入三條邊長,如果能構成三角形就計算周長和麵積
"""
判斷輸入的邊長能否構成三角形,如果能則計算出三角形的周長和麵積
"""
a= float(input('a='))
b= float(input('b='))
c= float(input('c='))
if a+b>c and a+c>b and b+c>a:
print('周長:%.2f' % (a+b+c))
p=(a+b+c)/2
area=(p*(p-a)*(p-b)*(p-c)) ** 0.5 # 海倫公式
print('面積:%.2f'%(area))
else:
print('不能構成三角形')