NameError when the variable exists - code execution

Hi there,
I’m quite new to Python and I have some doubts on how the code execution works.
For example, if I have:

letters = [“a”, “b”, “c”]
print(letters)

if I run the two lines separately on VS code, then for the second line I get the NameError: name ‘letters’ is not defined.

On the contrary, running the two lines together does not imply any problem.
But if letters is defined/assigned in the first line, then why running the two lines separate create a problem?

Thanks and sorry in advance if it sounds a “stupid question”.

What do you mean by “run the two lines separately”?

If you try to use a variable that does not exist, you should get that error. For example:

print(any_variable_that_does_not_exist)

It would also apply if you used the variable anywhere else:

new_variable = any_variable_that_does_not_exist + 2

Thanks for the reply.
I mean literally run only the first line of code

letters = [“a”, “b”, “c”]

and then run only

print(letters)

I may be biased from R where if I firstly define letters (run only first line) and then run only the print command, it shows me the desired output.
Hope it is clearer now.

Yes, but what do you mean by “only run”. Are you commenting out the other line? Are you using some special “run selected” function? I do not think any state is retained between runs if that is the case.

If you ran the lines one at a time in the Python REPL it should work just fine.

No, without commenting out the other line.
Just selecting the first and execute (control+otion+n) and then doing the same with the second one.

I just realize that if I run it in the interactive window in VS code, it works as expected. So it may be the way of execution (shift+enter) vs (control+otion+n)?

Thanks again

Yep, I think the way you executed it just makes completely isolated environments where the second run is not aware of the first one.

2 Likes