简体   繁体   English

python名称未定义,即使它是

[英]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,但是错误是NameError: name 'end' is not defined我什至尝试了将end NameError: name 'end' is not defined全局。

end is only assigned to if there was no ValueError . 仅当没有ValueError时才将end分配给。 If int() raises an exception, then the assignment never takes place . 如果int()引发异常,则分配永远不会发生

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. 要么在try 测试有效的end值(这样您就不会引发异常),要么为默认值指定第一个end

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: 例如,以下内容不会引发您的异常,并且如果输入的不是12则仍然提示用户重新输入数字:

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; 请注意,我移动的print()外侧except块; it'll be printed if an exception was thrown or when no break or exit() was executed. 如果抛出异常,或者没有执行breakexit() ,它将被打印出来。 Note that I used break here instead of continue to exit the while True loop; 注意,我在这里使用break而不是continue退出while True循环; continue would just start the next iteration, prompting the user to enter a number again. continue ,则只会开始下一个迭代,提示用户再次输入数字。

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. 如果int(input(...))失败,则会引发ValueError That happens before end is assigned. 这发生在分配end之前。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python:NameError:名称未定义,即使已定义 - Python: NameError: name is not defined even though it is defined 即使显式导入 Python 名称“os”也未定义 - Python name 'os' is not defined even though it is explicitly imported NameError: name 'self' 未定义,即使是? - NameError: name 'self' is not defined, even though it is? NameError:即使未定义全局名称“ interfaceName” - NameError: global name 'interfaceName' is not defined even though it is Python(Tkinter)中的范围错误:“名称'Sample_Name'未定义”,即使它被声明为全局 - Scope Error In Python (Tkinter): "name 'Sample_Name' is not defined", even though it is declared as global 名称“ClassName”未定义,即使我确定我正确导入(Python) - name “ClassName” is not defined even though im sure i imported correctly (Python) 即使我定义了名称“delta_scroll”,也没有定义它? - name 'delta_scroll' is not defined even though I defined it? 'NameError:即使已导入全局名称'subprocess',也未定义' - 'NameError: global name 'subprocess' is not defined' even though it is imported 即使名称'net_input'在全局中也未定义 - name 'net_input' is not defined even though it is in global “NameError: name 'redirect' is not defined”,即使导入了重定向 - “NameError: name 'redirect' is not defined” even though redirect is imported
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM