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
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
Share
Improve this question
edited Jan 18 at 22:03
wjandrea
32.9k9 gold badges69 silver badges96 bronze badges
asked Jan 18 at 22:01
ijustwantedtosayhiijustwantedtosayhi
297 bronze badges
4
|
1 Answer
Reset to default 0This 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
>>>
exec()
? e.g. this part: "The return value isNone
." – wjandrea Commented Jan 18 at 22:07None
, I just expected it to show me the same output as aprint ("asd")
would. But now that you said that, it occurs to me thatint
is 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 thatexec
doesn'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! – ijustwantedtosayhi Commented Jan 18 at 22:12exec
works the same as a .py script. If we write a 2 line .py file without theprint
, we wouldn't expect it to print anything. – tdelaney Commented Jan 18 at 22:44