gpt4 book ai didi

python - 除了 ValueError 在我的代码中不起作用我不知道为什么

转载 作者:太空宇宙 更新时间:2023-11-04 02:10:07 25 4
gpt4 key购买 nike

我包含了 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com