我添加了 ValueError 来确保用户输入一个整数,但它指出了未绑定(bind)的本地错误并指出该变量在赋值之前被引用
def bagTotal():
while True:
try:
bagCount = int(input("Now we just need the number of bags you wish to take with you: "))
except ValueError:
print("Please input a number")
print("")
if (bagCount <= 2):
print("As stated before the first bag is free")
print(name,",your total is","$%>2F"%ticket)
print("")
print("")
restart()
else:
bagTotal = (bagCount - 1) * bagFee
ticketTotal = bagTotal + ticketamount
print(name,", your new total is","$%.2f"%ticketTotal)
print("")
print("")
restart()
最佳答案
如果您收到 ValueError,程序将继续运行您的 if
语句等,然后再进入 while 循环的下一个循环。您只希望在没有错误的情况下运行该代码,因此您的代码应如下所示:
def bagTotal():
while True:
try:
bagCount = int(input("Now we just need the number of bags you wish to take with you: "))
if (bagCount <= 2):
print("As stated before the first bag is free")
print(name,",your total is","$%>2F"%ticket)
print("")
print("")
restart()
else:
bagTotal = (bagCount - 1) * bagFee
ticketTotal = bagTotal + ticketamount
print(name,", your new total is","$%.2f"%ticketTotal)
print("")
print("")
restart()
except ValueError:
print("Please input a number")
print("")
关于python - 除了 ValueError 在我的代码中不起作用我不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53879150/