簡體   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