我的代碼按照我想要的方式作業 - 除非輸入包含字母字符。如果是這樣,就是崩潰。我怎樣才能防止這種情況?我的代碼如下:
def main():
choice ='0'
while choice =='0':
print ("-" * 30 "MENU" "-" * 30)
print ("|" " " * 19 "1. Hourly to annual pay" " " * 20 "|")
print ("|" " " * 19 "2. Annual to hourly pay" " " * 20 "|")
print ("|" " " * 19 "3. Exit" " " * 36 "|")
print ("-" * 64)
choice = input ("Choose an option 1-3: ")
if choice =="1":
hourly = input ("Enter hourly pay: ")
annual = float (hourly) * 2080
print ("Annual pay is: ")
print ("{:0.2f}".format(annual))
main()
elif choice =="2":
a = input ("Enter annual pay: ")
h = float (a) / 2080
x = round(h, 2)
print ("{:0.2f}".format(x))
main()
elif choice =="3":
print ("Program exited gracefully.")
raise SystemExit(0)
else:
print ("Unrecognized command - choose 1-3")
main()
uj5u.com熱心網友回復:
嘗試將輸入轉換為浮點值時,您可以捕獲 ValueError。我修改了您的代碼以顯示它是如何完成的:
def get_float_input(prompt: str) -> float:
try:
data = input(prompt)
data = float(data)
return data
except ValueError:
raise ValueError('Please enter a valid number')
def main():
while True:
print("-" * 30 "MENU" "-" * 30)
print("|" " " * 19 "1. Hourly to annual pay" " " * 20 "|")
print("|" " " * 19 "2. Annual to hourly pay" " " * 20 "|")
print("|" " " * 19 "3. Exit" " " * 36 "|")
print("-" * 64)
choice = input("Choose an option 1-3: ")
if choice == "1":
try:
hourly = get_float_input("Enter hourly pay: ")
except ValueError as e:
print(e)
continue
annual = hourly * 2080
print("Annual pay is: ")
print("{:0.2f}".format(annual))
elif choice == "2":
try:
a = get_float_input("Enter annual pay: ")
except ValueError as e:
print(e)
continue
h = a / 2080
x = round(h, 2)
print("{:0.2f}".format(x))
elif choice == "3":
print("Program exited gracefully.")
raise SystemExit(0)
else:
print("Unrecognized command - choose 1-3")
if __name__ == '__main__':
main()
uj5u.com熱心網友回復:
您可以做的最好的事情是在將輸入資料轉換為浮點數時使用例外處理。它將捕獲所有無法轉換為浮點數的無效輸入。
def main():
choice ='0'
while choice =='0':
print ("-" * 30 "MENU" "-" * 30)
print ("|" " " * 19 "1. Hourly to annual pay" " " * 20 "|")
print ("|" " " * 19 "2. Annual to hourly pay" " " * 20 "|")
print ("|" " " * 19 "3. Exit" " " * 36 "|")
print ("-" * 64)
choice = input ("Choose an option 1-3: ")
if choice =="1":
hourly = input ("Enter hourly pay: ")
try:
annual = float (hourly) * 2080
print ("Annual pay is: ")
print ("{:0.2f}".format(annual))
except:
print("Invalid Input")
main()
elif choice =="2":
a = input ("Enter annual pay: ")
try:
h = float (a) / 2080
x = round(h, 2)
print ("{:0.2f}".format(x))
except:
print("Invalid Input")
main()
elif choice =="3":
print ("Program exited gracefully.")
raise SystemExit(0)
else:
print ("Unrecognized command - choose 1-3")
main()
uj5u.com熱心網友回復:
我認為您必須使用while True來運行程式,直到用戶輸入 3(無限回圈)。為了處理這個問題,您可以使用 try except 陳述句。所以,你的代碼需要是這樣的
def main():
print ("-" * 30 "MENU" "-" * 30)
print ("|" " " * 19 "1. Hourly to annual pay" " " * 20 "|")
print ("|" " " * 19 "2. Annual to hourly pay" " " * 20 "|")
print ("|" " " * 19 "3. Exit" " " * 36 "|")
print ("-" * 64)
try:
while True:
choice = input ("Choose an option 1-3: ")
if choice =="1":
hourly = input ("Enter hourly pay: ")
annual = float (hourly) * 2080
print ("Annual pay is: ")
print ("{:0.2f}".format(annual))
elif choice =="2":
a = input ("Enter annual pay: ")
h = float (a) / 2080
x = round(h, 2)
print ("{:0.2f}".format(x))
elif choice =="3":
print ("Program exited gracefully.")
raise SystemExit(0)
except ValueError:
print ("Unrecognized command - choose 1-3")
main()
uj5u.com熱心網友回復:
每當我想要數字輸入時,我都會使用一個方便的助手。
def get_num(prompt="Enter number: "):
"""
(str) -> num
Outputs a prompt and loops until a valid number is
entered by the user, at which point that value is
returned and the function terminates
"""
while True:
num = input(prompt)
try:
num = float(num)
return num
except:
print("Must enter a valid number")
def main():
while True:
print ("-" * 30 "MENU" "-" * 30)
print ("|" " " * 19 "1. Hourly to annual pay" " " * 20 "|")
print ("|" " " * 19 "2. Annual to hourly pay" " " * 20 "|")
print ("|" " " * 19 "3. Exit" " " * 36 "|")
print ("-" * 64)
choice = get_num("Choose an option 1-3: ")
if choice == 1:
hourly = get_num("Enter hourly pay: ")
annual = hourly * 2080
print ("Annual pay is: ")
print ("{:0.2f}".format(annual))
# main() recursive call- don't do this
elif choice == 2:
a = get_num("Enter annual pay: ")
h = a / 2080
x = round(h, 2)
print ("{:0.2f}".format(x))
main()
elif choice == 3:
print ("Program exited gracefully.")
raise SystemExit(0)
else:
print ("Unrecognized command - choose 1-3")
repeat = input("Enter Y to repeat or any other key to quit: ")
if repeat.lower() != "y":
break
main()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/324105.html
上一篇:處理例外時如何避免部分執行代碼?
