本題目節選自國外某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.")
輸出的結果如下所示;

歡迎有問題咨詢!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/162494.html
標籤:Python
