pythondefined

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

Solution

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