標籤:lis mos Null 字元串 wro last enter 類型 自動化 put
條件判斷電腦之所以能做很多自動化的任務,因為它可以自己做條件判斷。 比如,輸入使用者年齡,根據年齡列印不同的內容,在Python程式中,用if語句實現: age = 20if age >= 18: print(‘your age is‘, age) print(‘adult‘)根據Python的縮排規則,如果if語句判斷是True,就把縮排的兩行print語句執行了,否則,什麼也不做。 也可以給if添加一個else語句,意思是,如果if判斷是False,不要執行if的內容,去把else執行了: age = 3if age >= 18: print(‘your age is‘, age) print(‘adult‘)else: print(‘your age is‘, age) print(‘teenager‘)注意不要少寫了冒號:。 當然上面的判斷是很粗略的,完全可以用elif做更細緻的判斷: age = 3if age >= 18: print(‘adult‘)elif age >= 6: print(‘teenager‘)else: print(‘kid‘)elif是else if的縮寫,完全可以有多個elif,所以if語句的完整形式就是: if <條件判斷1>: <執行1>elif <條件判斷2>: <執行2>elif <條件判斷3>: <執行3>else: <執行4>if語句執行有個特點,它是從上往下判斷,如果在某個判斷上是True,把該判斷對應的語句執行後,就忽略掉剩下的elif和else,所以,請測試並解釋為什麼下面的程式列印的是teenager: age = 20if age >= 6: print(‘teenager‘)elif age >= 18: print(‘adult‘)else: print(‘kid‘)if判斷條件還可以簡寫,比如寫: if x: print(‘True‘)只要x是非零數值、非Null 字元串、非空list等,就判斷為True,否則為False。 再議 input最後看一個有問題的條件判斷。很多同學會用input()讀取使用者的輸入,這樣可以自己輸入,程式運行得更有意思: birth = input(‘birth: ‘)if birth < 2000: print(‘00前‘)else: print(‘00後‘)輸入1982,結果報錯: Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: unorderable types: str() > int()這是因為input()返回的資料類型是str,str不能直接和整數比較,必須先把str轉換成整數。Python提供了int()函數來完成這件事情: s = input(‘birth: ‘)birth = int(s)if birth < 2000: print(‘00前‘)else: print(‘00後‘)再次運行,就可以得到正確地結果。但是,如果輸入abc呢?又會得到一個錯誤資訊: Traceback (most recentcall last): File "<stdin>", line 1, in <module>ValueError: invalid literal for int() with base 10: ‘abc‘原來int()函數發現一個字串並不是合法的數字時就會報錯,程式就退出了。 如何檢查並捕獲程式運行期的錯誤呢?後面的錯誤和調試會講到。 練習小明身高1.75,體重80.5kg。請根據BMI公式(體重除以身高的平方)幫小明計算他的BMI指數,並根據BMI指數:
- 低於18.5:過輕
- 18.5-25:正常
- 25-28:過重
- 28-32:肥胖
- 高於32:嚴重肥胖
用if-elif判斷並列印結果: # -*- coding: utf-8 -*- from __future__ import division a = input(‘please enter your height :‘)b = input(‘please enter your weight :‘)BMI = float(b/(a*a))if BMI < 18.5: print(‘your weight too light‘)elif 18.5 <= BMI<25: print(‘your weight is normal‘)elif 25 <= BMI <= 28: print(‘your weight too heavy‘)elif 28 < BMI <= 32: print(‘your weight hyperadiposity‘)elif BMI > 32: print(‘your weight too hyperadiposity‘) else: print(‘your enter is wrong’) 小結條件判斷可以讓電腦自己做選擇,Python的if...elif...else很靈活。
python 之條件判斷