0

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
asked Jan 18, 2025 at 22:01
4
  • 2
    Did you read the docs about exec()? e.g. this part: "The return value is None." Commented Jan 18, 2025 at 22:07
  • Why are you expecting it to behave like the REPL? Commented Jan 18, 2025 at 22:10
  • 1
    I know the return value is None, I just expected it to show me the same output as a print ("asd") would. But now that you said that, it occurs to me that int 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 that exec 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 use eval. Thanks for the help! Commented Jan 18, 2025 at 22:12
  • 1
    exec works the same as a .py script. If we write a 2 line .py file without the print, we wouldn't expect it to print anything. Commented Jan 18, 2025 at 22:44

1 Answer 1

0

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
>>>
answered Jan 18, 2025 at 22:58
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.