我包含ValueError以确保用户输入一个整数,但是它声明了未绑定的本地错误,并指出在赋值之前已引用了变量
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()
答案 0 :(得分:2)
如果要获取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("")
答案 1 :(得分:0)
这是修改后的代码,请检查,我注释了几行,还使用了一些变量 我在您的代码中看到可以使其在我的系统中正常工作。
def bagTotal():
# The below 4 initializations are just
# to stop errors in your problem, you use your own values
bagFee = 100
ticketamount = 60
name = 'Rampel Jons'
ticket = 70
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("")
# call
bagTotal()
# Now we just need the number of bags you wish to take with you: 5
# Rampel Jons , your new total is $460.00
# Now we just need the number of bags you wish to take with you: 7
# Rampel Jons , your new total is $660.00
# Now we just need the number of bags you wish to take with you: 9
# Rampel Jons , your new total is $860.00
# Now we just need the number of bags you wish to take with you: fjjfjf
# Please input a number
# Now we just need the number of bags you wish to take with you: