python基礎(chǔ)-分支與判斷

if語句的使用

在Python中,要構(gòu)造分支結(jié)構(gòu)可以使用if、elifelse關(guān)鍵字。
所謂關(guān)鍵字就是有特殊含義的單詞,像if和else就是專門用于構(gòu)造分支結(jié)構(gòu)的關(guān)鍵字,很顯然你不能夠使用它作為變量名
下面的例子中演示了如何構(gòu)造一個(gè)分支結(jié)構(gòu)

"""
分段函數(shù)求值:
        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:
    y = 5 * x + 3
else:
    y = x + 2

print('y={:.2f}'.format(y))

當(dāng)然根據(jù)實(shí)際開發(fā)的需要,分支結(jié)構(gòu)是可以嵌套的
在if的內(nèi)部構(gòu)造出一個(gè)新的分支結(jié)構(gòu),同理elif和else中也可以再構(gòu)造新的分支,我們稱之為嵌套的分支結(jié)構(gòu)

注意

if語句執(zhí)行有個(gè)特點(diǎn),它是從上往下判斷,如果在某個(gè)判斷上是True,把該判斷對應(yīng)的語句執(zhí)行后,就忽略掉剩下的elif和else,所以,請測試并解釋為什么下面的程序打印的是teenager

age=20

if age>6:
    print('teenager')
# 可以改成if 查看結(jié)果
elif age>18: 
    print('adult')
else:
    print('kid')

練習(xí)

練習(xí)1:英制單位與公制單位互換

進(jìn)度1in=2.54cm

value = float(input('請輸入長度: '))
unit = input('請輸入單位: ')
if unit in ['in', '英寸']:
    print('%f英寸 = %f厘米' % (value, value * 2.54))
elif unit in ['cm', '厘米']:
    print('%f厘米 = %f英寸' % (value, value / 2.54))
else:
    print('請輸入有效的單位')
請輸入長度: 5
請輸入單位: in
5.000000英寸 = 12.700000厘米

練習(xí)2:百分制成績轉(zhuǎn)等級制

百分制成績轉(zhuǎn)等級制成績
90分以上 --> A
80分~89分 --> B
70分~79分 --> C
60分~69分 --> D
60分以下 --> E

score = float(input('請輸入成績: '))
if score > 100:
    grade = '優(yōu)秀'
    print('你不會這么聰明吧')
elif score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
elif score >= 70:
    grade = 'C'
elif score >= 60:
    grade = 'D'
else:
    grade = 'E'
print('對應(yīng)的等級是:', grade)
請輸入成績: 105
你不會這么聰明吧
對應(yīng)的等級是: 優(yōu)秀

練習(xí)3:實(shí)現(xiàn)一個(gè)個(gè)人所得稅計(jì)算器

輸入月收入和五險(xiǎn)一金計(jì)算個(gè)人所得稅
起征點(diǎn)5000元

含稅級距 稅率
應(yīng)納稅額≤3000 3%
3000<應(yīng)納稅額≤12000 10%
12000<應(yīng)納稅額≤25000 20%
25000<應(yīng)納稅額≤35000 25%
35000<應(yīng)納稅額≤55000 30%
55000<應(yīng)納稅額≤80000 35%
應(yīng)納稅額>80000 45%
salary = float(input('本月收入: '))
insurance = float(input('五險(xiǎn)一金: '))
diff = salary - insurance - 5000
if diff <= 0:
    rate = 0
    deduction = 0
elif diff <= 3000:
    rate = 0.03
    deduction = 0
elif diff <= 12000:
    rate = 0.1
    deduction = 105
elif diff <= 25000:
    rate = 0.2
    deduction = 555
elif diff <= 35000:
    rate = 0.25
    deduction = 1005
elif diff <= 55000:
    rate = 0.3
    deduction = 2755
elif diff <= 80000:
    rate = 0.35
    deduction = 5505
else:
    rate = 0.45
    deduction = 13505
tax = abs(diff * rate - deduction)
print('個(gè)人所得稅: ¥%.2f元' % tax)
print('實(shí)際到手收入: ¥%.2f元' % (diff + 3500 - tax))
微信關(guān)注.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容