繁体   English   中英

NameError 但变量已定义

[英]NameError but variable is defined

我正在写这篇文章作为 Python 练习练习。 该循环应该接受用户输入并使用 eval function 对其进行评估,并在用户输入done时中断循环。 返回在输入done之前的输入。

def eval_loop():
    while True:
        x = ('done')
        s = (input("write a thing. "))
        s1 = s
        print(eval(s))
        if s == x:
            break
    return s1

eval_loop()

该代码适用于诸如510 + 3等输入。但是当我输入done作为输入时,我收到此错误:

Traceback (most recent call last):
  File "C:/Users/rosem/Progs/1101D4.py", line 11, in <module>
    eval_loop()
  File "C:/Users/rosem/Progs/1101D4.py", line 6, in eval_loop
    print(eval(s))
  File "<string>", line 1, in <module>
NameError: name 'done' is not defined

你不能像那样评估“文本”。 老实说,我建议您无论如何都不要使用 eval 来解决这样的问题。 但是,如果必须,您可以切换顺序并尝试/捕获。

def eval_loop():
    while True:
        x = ('done')
        s = input("write a thing. ")
        s1 = s
        #check if input is 'done'
        if s == x:
            break
        else:
            try:
                #evaluate
                print(eval(s))
            #error caused by s being something like 'foo'
            except NameError:
                pass 
    return s1
eval_loop()

NameError: name 'done' is not defined正在发生,因为您没有在使用eval之前检查输入是否已done 而是试试这个:

def eval_loop():
    while True:
        s = (input("write a thing. "))
        s1 = s
        if s == 'done':
            break
        print(eval(s))

    return s1

eval_loop()

如果您不检查,则 python 会尝试“运行” done ,这会引发错误。

另请参阅 Brain 的评论和其他答案。

暂无
暂无

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

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