Rose Mullins
Rose Mullins

Reputation: 23

NameError but variable is defined

I'm writing this as a Python practice exercise. The loop is supposed to take user input and evaluate it using the eval function, and break from the loop when the user enters done. Returns the input that was prior to the input 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()

The code works fine for input such as 5, 10 + 3, etc. But when I enter done as input, I get this error:

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

Upvotes: 1

Views: 585

Answers (2)

Have a nice day
Have a nice day

Reputation: 1005

The NameError: name 'done' is not defined is happening because you are not checking to see if the input was done before using eval. Instead try this:

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

    return s1

eval_loop()

If you don't check then python tries to "run" done, which throws the error.

Also see Brain's comment and the other answer.

Upvotes: 1

Buddy Bob
Buddy Bob

Reputation: 5889

You can't eval 'text' like that. And I honestly suggest you don't use eval for such a problem anyway. But if you had to, you can switch the order and have a try/catch.

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()

Upvotes: 3

Related Questions