1-6 鍵盤輸入

用Python的內建函式input()可以由鍵盤輸入資料,但是input()的輸入內容會被當作字串,如果要得到整數值可以再用int()函式轉換。

print('請輸入年齡:')
age = int(input())  #輸入年齡

#80歲以上或10歲以下少收50元
if 10 <= age <= 60:
    price = 200
else:
    price = 150
    
print(price)

使用input()輸入資料時,我們很難預期使用者是否會輸入正確的整數?例如使用者輸入「ABC」,這個值將沒有辦法正確的轉換成整數,程式將出現執行錯誤而中斷。為了避免程式執行的錯誤,我們可以用tryexcept指令補捉不可預期的錯誤。

try:
    print('請輸入年齡:')
    age = int(input())  #輸入年齡

    #80歲以上或10歲以下少收50元
    if 10 <= age <= 60:
        price = 200
    else:
        price = 150
        
    print(price)
except:
    print('輸入錯誤!')

Python會先執行try之間的程式碼,但如果程式發生錯誤時,就會跳入except指令的區段,不會出現程式執行錯誤的中斷。

Last updated