exec("a=1\nprint(a)") prints 1, as expected. However exec("a=1\na") does not print out 1. Why is that?
I expect it to print out 1 because in the Python interpreter, whenever I enter a variable name, it prints out its value:
>>> a = 1
>>> a
1
wjandrea
34k10 gold badges69 silver badges107 bronze badges
1 Answer 1
This is because exec() always run the code via execution, not interpreter. If you want to print like an interpreter, than you can use eval:
>>> a = 1
>>> eval("a")
1
>>>
Sign up to request clarification or add additional context in comments.
Comments
lang-py
exec()? e.g. this part: "The return value isNone."None, I just expected it to show me the same output as aprint ("asd")would. But now that you said that, it occurs to me thatintis a class, and I guess in the Python interpreter when I enter any variable or a literal integer, it returns that value and that's why it appears there. In which case, it makes sense thatexecdoesn't show me the value. I didn't realize why the interpreter showed back the value I typed into it, but if it's a return value, then yeah... I could also useeval. Thanks for the help!execworks the same as a .py script. If we write a 2 line .py file without theprint, we wouldn't expect it to print anything.