I am a beginner in python. Found this while solving exercise in the book Think Python. In this code eval_loop function iteratively prompts the user, takes the resulting input and evaluates it using eval, and prints the result. It should continue until the user enters 'done', and then return the value of the last expression it evaluated. My doubt is:
Eval must have a string as its argument, but this code works even when we input non string like 5+4, it prints 9. Since we are not converting the input into a string anywhere, Please tell me how is it not producing an error?
def eval_loop():
result=0
while True:
s = input('>>>')
if s == 'done':
break
result = eval(s)
print(result)
print(result)
eval_loop()
Update:
OK I get it now, the function input returns a string. But now I have one more doubt:
If input function returns a string then why does it produce an error when I give input as - hello, without any inverted commas around it. It gives NameError: name 'hello' is not defined. If input returns a string shouldn't hello be converted to a string too?
Someone please help me out, this is getting very confusing. :(
inputreturns a string.evalis included ininputevalevaluates the expression... I'd recommendsimpleevalinstead (external package) which doesn't have any security issues...hellogets converted to a string frominput(), but when you try toeval()the string you're evaluating it as a variable (e.g.eval("hello")) and since you don't have ahellovariable defined you get the error.eval("'hello'")so it doesn't try to find a variable with such name. Think ofeval()as if you were actually typing the code - if you type in your code'hello'nothing will happen (it's a string literal so it will just be ignored since its not assigned to anything) but if you typehelloit will attempt to find a variable namedhelloand raise aNameError.