在这个程序中,如果用户输入字符串输入,程序将不会运行,用户将得到一个错误。我如何开发我的程序来告诉用户输入错误?你能帮我解决这个问题吗?
summation = 0
while True:
user_input = input("Enter your input \n")
if user_input == "done":
break
else:
summation = summation + float(user_input)
print("End \n", "SUMMATION = ", summation)
"conention.py/while.py"
Enter your input
Hi
Traceback (most recent call last):
File "c:\Users\ASUS\Desktop\python\name conention.py\while.py", line 7,
in <module> summation = summation + float(user_input)
ValueError: could not convert string to float: 'Hi'
PS C:\Users\ASUS\Desktop\python> 发布于 2021-11-09 18:58:13
你运行float("Hi"),这就产生了问题。
您应该使用try/except来捕获错误并执行某些操作或跳过它。
例如。
summation = 0
while True:
user_input = input("Enter your input \n")
if user_input.lower() == "done":
break
try:
summation = summation + float(user_input)
print("End \n", "SUMMATION = ", summation)
except ValueError:
print('It is not float value:', user_input)https://stackoverflow.com/questions/69903471
复制相似问题