我是使用python进行编程的初学者,并且对异常如何工作感到困惑。我正在为餐馆创建一个菜单列表和字典,如果用户键入无效数字或字符串,我需要它除了值Error以及再次询问用户但仍然得到值错误代码
while True:
try:
itemCost = float(raw_input("Please enter the cost of this item (ex: 22.45): "))
if itemCost < 0: print "Invalid Number, please try again"
except ValueError:
print "Invalid Number, please try again"
except NameError:
print "Invalid Number, please try again"
except SyntaxError:
print "Invalid Number, please try again"
更新
这就是我输入但仍然得到一个值错误代码,因为我使用了一个字符串而不是一个浮点数,但希望它给用户一个错误信息。
Please enter the menu item name (quit to exit): Chicken
Please enter the cost of this item (ex: 22.45): rrr
Traceback (most recent call last):
File "/Users/Stan/Documents/Intro to Programming/Program Project #2.py", line 14, in <module>
itemCost = float(raw_input("Please enter the cost of this item (ex: 22.45): "))
ValueError: could not convert string to float: rrr
Process finished with exit code 1