【问题标题】:How to prevent python program crash when receiving alphabetical characters接收字母字符时如何防止python程序崩溃
【发布时间】:2021-10-10 01:09:31
【问题描述】:
我的代码按我想要的方式工作 - 除非输入包含字母字符。如果是这样,就是崩溃。我怎样才能防止这种情况?我的代码如下:
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()
【问题讨论】:
标签:
python
python-3.x
exception
crash
integer
【解决方案1】:
您可以在尝试将输入转换为浮点值时捕获 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()
【解决方案2】:
您可以做的最好的事情是在将输入数据转换为浮点数时使用异常处理。它将捕获所有无法转换为浮点数的无效输入。
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()
【解决方案3】:
我认为你必须使用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()
【解决方案4】:
每当我想输入数字时,我都会使用方便的助手。
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()