我刚刚创建了一个python字典,它是可执行文件。如果有人在里程表读数中放入文本而不是数字,如何验证用户输入以提供异常错误?下面是代码。感谢您的反馈团队。
/Users/aaronbratcher/Library/Developer/CoreSimulator/Devices/3E6F7BD3-482B-4A90-B3C7-C0CC8412A5AC/data/Documents/test.db
答案 0 :(得分:0)
你可以这样做:
def get_number(hint):
while True:
try:
value = int(input(hint))
except ValueError:
print('Please input a number')
continue
if value<0:
print('Please input a positive value')
continue
else:
break
return value
Auto_details = {'Car brand': input('Car brand:'),
'Car model': input('Car model:'),
'Model Year': input('Model Year:'),
'Starting odometer reading': get_number('Starting odometer reading:'),
'Ending odometer reading': get_number('Ending odometer reading:'),
'Miles per gallon': get_number('Miles per gallon:'),
}
print(Auto_details)
input ('Thank you. Please press Enter to exit')
答案 1 :(得分:0)
我没有尝试过,但可能会有效。
Auto_details = {}
phrases=[
["Car brand",False], ["Car model",False],
["Model year",False],["Starting odometer reading",True],
["Ending odometer reading",True],["Miles per gallon",True]
]
for phrase in phrases:
answer=input(phrase[0])
if phrase[1]:
while True:
if answer.isdigit():
answer=int(answer)
break
answer=input(phrase[0])
Auto_details[phrase[0]]=answer