简体   繁体   中英

python name not defined even though it is

I know this is basic but i actually don't even know what I've done wrong.

while True:
    try:
        end=int(input("If You Dont Want To Buy Anything Press 1 To Exit\nOr If You Would Like To Try Again Please Press 2"))
    except ValueError:
        print("\nPlease Enter Only 1 Or 2")
    if end==1:
        exit()
    elif end==2:
        continue

I have literally defined end at the start and yet the error is NameError: name 'end' is not defined I've even tried making end a global.

end is only assigned to if there was no ValueError . If int() raises an exception, then the assignment never takes place .

Either test for valid end values inside the try (so that you know no exception was raised), or assign a default value to end first.

For example, the following will not throw your exception and still prompt the user to re-enter the number if anything other than 1 or 2 was entered:

while True:
    try:
        end=int(input("If You Dont Want To Buy Anything Press 1 To Exit\nOr If You Would Like To Try Again Please Press 2"))
        if end==1:
            exit()
        elif end==2:
            break
    except ValueError:
        pass
    print("\nPlease Enter Only 1 Or 2")

Note that I moved the print() to be outside the except block; it'll be printed if an exception was thrown or when no break or exit() was executed. Note that I used break here instead of continue to exit the while True loop; continue would just start the next iteration, prompting the user to enter a number again.

Others have explained the problem; here's a canonical solution. This matches the way many of us regard the process: - grab a response - until I get a legal response - ... tell the user what's wrong - ... get a new response

input_prompt = "If You Don't Want To Buy Anything Press 1 To Exit\nOr If You Would Like To Try Again Please Press 2"
response = input(input_prompt)
while response != '1' and response != '2':
    print("\nPlease Enter Only 1 Or 2")
    response = input(input_prompt)
end = int(reponse)

This has no unnatural loop exits (harder to follow and maintain), and no exception processing (slow).

它尝试为end分配一个值,但是捕获到ValueError,并且在except之后尝试查看“ end”是什么,但是由于异常,它从未被分配任何值。

If int(input(...)) fails, a ValueError is raised. That happens before end is assigned. Add another control statement in the error handling, for instance

while True:
    try:
        end=int(input("If You Dont Want To Buy Anything Press 1 To Exit\nOr If You Would Like To Try Again Please Press 2"))
    except ValueError:
        print("\nPlease Enter Only 1 Or 2")
        continue  # ask again
    if end==1:
        exit()
    elif end==2:
        continue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM