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

标签 python python-3.x valueerror

我添加了 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/

相关文章:

python - YML文件打印错误的次数

python - 按顺序依次读取文件

python - Python 3 的 WSGI 服务器(PEP 3333)

python身份危机为什么l或x复制0而不产生新的0

python - 为什么这个查询不能从 python 到 SQL?

python - 使用 tflearn 构建 CNN

python - 从Docker容器中的Django + Celery对API超时进行故障排除

python - 将 .lower() 函数应用于列表中所有单词大小写的字符串

python - ValueError:格式字符串中无法识别的字符 a

python - 如何将我的输出附加到 python 中的特定位置?