Python Forum
NameError: name “x” is not defined ... even though x is defined
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
NameError: name “x” is not defined ... even though x is defined
#6
There are lots of ways to run code in VSCode.

Are you using "Run Selection/Line in Python Terminal" from the context menu that pops up when you right click in the text editor view? I get this error of I run your program that way without making a selection.
x = 5
print(x)
Error:
File "<stdin>", line 1, in <module> NameError: name 'x' is not defined
Notice the error says the problem is in line 1, but obviously the error is in line 2. If you don't make a selection, this command uses the line containing the cursor. So it ran this program
print(x)
And this program has an error in line 1.

"Run Python File in Terminal" from the context menu works for me.

"Run XXX in Interactive Window" requires I install ipykernal to use. When I select this option it creates a jupyter like interface where I enter python code in cells.

I usually use the run arrow near the upper right corner ("Run Python File in Terminal") or the "Start Debugging" or "Run Without Debugging" options under the "Run" menu. All of these run your program without problems.

What extensions do you have installed in VSCode? I have Python and PyLance. I also installed Jupyter because I wanted to get a feel for how that works. I think installing the Jupyter extension is why I get the "Run XXX in Interactive Window" choices in the code context menu.

So how are you running your program when you have this problem?
campjaybellson likes this post
Reply


Messages In This Thread
RE: NameError: name “x” is not defined ... even though x is defined - by deanhystad - Oct-19-2021, 07:24 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Question Variable not defined even though it is CoderMerv 3 402 Mar-28-2024, 02:13 PM
Last Post: Larz60+
  I'm getting a NameError: ...not defined. vonArre 2 443 Mar-24-2024, 10:25 PM
Last Post: vonArre
  Variable is not defined error when trying to use my custom function code fnafgamer239 4 671 Nov-23-2023, 02:53 PM
Last Post: rob101
  Printing the variable from defined function jws 7 1,491 Sep-03-2023, 03:22 PM
Last Post: deanhystad
  'answers 2' is not defined on line 27 0814uu 4 812 Sep-02-2023, 11:02 PM
Last Post: 0814uu
  tk is not defined jip31 8 10,705 Aug-03-2023, 05:01 PM
Last Post: tralfazy
  Simple Question - ' defined as "a". ?' Ryan012 10 1,802 May-27-2023, 06:03 PM
Last Post: Ryan012
  Badly defined python code? Ken76 2 686 May-25-2023, 11:05 PM
Last Post: DigiGod
  "Name is not defined" when running a class lil_e 6 4,326 Jan-12-2023, 11:57 PM
Last Post: lil_e
  Getting NameError for a function that is defined JonWayn 2 1,170 Dec-11-2022, 01:53 PM
Last Post: JonWayn

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020