Python拋出異常之后返回try語句,直到沒有異常出現


本題目節選自國外某top50高校Python練習題庫,重點在於我們返回try語句的方法,而不是題目給出的背景。假設我們寫一個程序,可以將輸入的身高厘米數轉化為英寸,如果遇到了負數,字母,中文等則拋出異常,並輸出“Only positive numeric inputs are accepted. Please try again.”,最后再返回到輸入input函數當中,要求用戶再次進行輸出(重點)。一個人的身高只能是正數。如果遇到了正數,則數值輸入正確,開始進行計算,計算完成后輸出“You are x feet y inches tall!”,x和y分別代表了計算之后的值。英文原文如下,感興趣的可以看看:

 

 

 

 最開始我嘗試了用函數來解決這個問題,表面上看起來是對的,但是很快掛了,因為進行第二次輸入異常值的時候,程序會報錯,正確的應該是只要有錯誤值,就不斷要求用戶進行輸入新的正確的值。用函數進行接收異常的except代碼塊里再次執行一個接收數字再進行計算的calculation()函數,因為這樣except代碼塊里的calculation()函數並不在try語句里,無法用expect進行接收。如下所示:

cm_to_inches = 0.393791
inches_to_feet = 12

def calculation():
        height_cm = float(input('Enter your height in cm: '))
        if height_cm < 0:
            raise ValueError()
        
        feet = height_cm * cm_to_inches // inches_to_feet
        inch = height_cm * cm_to_inches % inches_to_feet
        print("You are {:.0f} feet {:.0f} inches tall!".format(feet, inch))
    

try:
        calculation()
        
except ValueError:
        print("Only positive numeric inputs are accepted. Please try again.")
        calculation()

后來我想了一會兒,廢除函數,直接利用while循環就可以讓程序只要拋出異常就再次執行try代碼塊的語句,如果輸入數字判斷成功,沒有異常,則終止循環,使用break語句即可。程序如下;

cm_to_inches = 0.393791
inches_to_feet = 12

while True:
    try:
        height_cm = float(input('Enter your height in cm: '))
        if height_cm < 0:
            raise ValueError()
        
        feet = height_cm * cm_to_inches // inches_to_feet
        inch = height_cm * cm_to_inches % inches_to_feet
        print("You are {:.0f} feet {:.0f} inches tall!".format(feet, inch))
        break
    except ValueError:
        print("Only positive numeric inputs are accepted. Please try again.")

輸出的結果如下所示;

 

 歡迎有問題咨詢!


免責聲明!

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



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