skip to Main Content

I cannot get my VS Code terminal to communicate properly with the file editor window. Every time I call a variable, which I have defined, I get a traceback error saying that it the variable is not defined. This is what I am trying to reference, I have made sure to save the file (many times), as well as make sure everything is being interpreted as python code in the terminal.

greeting = "hello, Python"

This is the error that comes back when I try to call the variable (I just used print as an example):

>>> print(greeting)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'greeting' is not defined

any help would be greatly appreciated! (this is my first time using python in VS code, I have only used VS code for html so this is new to me!)

3

Answers


  1. If you try to put the print line before the variable, it’ll return that error. It will also do that if you try print(greeting) as a stand-alone execution. Try:

    greeting = "Hello, Python!"
    print(greeting)
    
    Login or Signup to reply.
  2. Terminals and scripts are different. If you are in a shell terminal then you can execute commands like py name.py to run scripts.

    enter image description here

    If you are in a python interactive terminal, then you can type and run python code directly. For example the following

    enter image description here

    If you are just starting to use python in VS code, it is helpful to read the starting documentation. Install the Python extension and use Run Python File to execute the script. This eliminates the need for you to manually type the command

    enter image description here

    Use the shortcut Shift+Enter to open an interactive terminal and execute the selected code, also without you having to manually type the code.

    Login or Signup to reply.
  3. It looks like the error is occurring in an interactive Python session (REPL) where the variable ‘greeting’ is not recognized. Ensure you are running the entire Python script in the terminal rather than entering individual lines in the interactive session.

    Save your Python file containing the ‘greeting’ variable and run the script using a command like:

    python filename.py
    

    Replace "filename.py" with the actual name of your Python file. This should execute the script, and you should be able to print the ‘greeting’ variable without encountering the NameError.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search