кроме ValueError не работает в моем коде, я не знаю, почему - PullRequest
0 голосов
/ 21 декабря 2018

Я включил 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()

Ответы [ 2 ]

0 голосов
/ 21 декабря 2018

Вот модифицированный код, пожалуйста, проверьте, я прокомментировал несколько строк, а также использовал некоторые переменные, которые я видел в вашем коде, чтобы он работал в моей системе.

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:
0 голосов
/ 21 декабря 2018

если вы получите 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("")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...