我有这个简单的项目要做.这是我到目前为止的代码,它工作得非常好.但如果有人输入字母或未知符号,程序会崩溃.如果输入错误的内容,如何进行此错误验证并显示或打印消息?
def excercise5():
print("Programming Excercise 5")
print("This program calculates the cost of an order.")
pound = eval(input("Enter the weight in pounds: "))
shippingCost = (0.86 * pound) + 1.50
coffee = (10.50 * pound) + shippingCost
if pound == 1:
print(pound,"pound of coffee costs $", coffee)
else:
print(pound,"pounds of coffee costs $", coffee)
print()
excercise5()
Run Code Online (Sandbox Code Playgroud)
我建议不要使用eval.从安全角度来看,它并不好.只需显式转换为所需类型:
pound = float(input("Enter the weight in pounds: "))
Run Code Online (Sandbox Code Playgroud)
要处理无效输入:
try:
pound = float(input("Enter the weight in pounds: "))
except ValueError:
print('Invalid input.')
return
# the rest of the code
Run Code Online (Sandbox Code Playgroud)
要么:
try:
pound = float(input("Enter the weight in pounds: "))
except ValueError:
print('Invalid input.')
else:
# the rest of the code
Run Code Online (Sandbox Code Playgroud)
您还可以将输入包装在无限循环中,该循环将在成功转换时终止:
while True:
try:
pound = float(input("Enter the weight in pounds: "))
except ValueError:
print('Invalid input. Try again.')
else:
break
# do the rest with `pound`
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5302 次 |
| 最近记录: |