-2

I wrote a simple piece of code in VScode but when I run it in the terminal an error pops up saying the variable is not defined. however when I manually press the run code button the code runs without any errors.

The code:

name = input("what is your name? ")
print("hello,", name)

the error message:

$ python hello.py
what is your name? ted
Traceback (most recent call last):
  File "hello.py", line 1, in <module>
    name = input("what is your name? ")
  File "<string>", line 1, in <module>
NameError: name 'ted' is not defined
rioV8
  • 24,506
  • 3
  • 32
  • 49
Nej
  • 1
  • 1
  • 1
    Please post your code, avoid links to images of code. – Beatdown Jun 26 '22 at 22:17
  • 4
    Please add code and error message as text, not as a screenshot. Concerning your problem: You try to run your code with Python 2. `input` is different in Python 2. You can even say that it's dangerous in Python 2. You might need to use `python3` to start your script. – Matthias Jun 26 '22 at 22:17
  • 2
    Try using `python3 hello.py` instead of `python hello.py` – Haoliang Jun 26 '22 at 22:18
  • thanks that seemed to work. But why was python hello.py working before but not now – Nej Jun 26 '22 at 22:24
  • 1
    A Python 2 interpreter is running the code at the bottom with the error message. For Python 2 use `raw_input()` instead of `input()`. – martineau Jun 26 '22 at 22:27
  • on Mac the default `python` command is Python2 – rioV8 Jun 27 '22 at 07:53
  • Please see https://stackoverflow.com/questions/21122540 and/or https://stackoverflow.com/questions/1093322. – Karl Knechtel Jul 05 '22 at 07:23

1 Answers1

0

It looks like you have multiple python versions installed on your machine, and your computer's default python version should be python2 (perhaps related to system environment variables). You can check the version with py -V.

It is recommended that you use a virtual environment and keep only one python version in each virtual environment. When you select an interpreter ( Ctrl + Shift + P --> Python: Select Interpreter), the new terminal ( Ctrl + Shift + ` ) will automatically activate the virtual environment.

Virtual environments are very useful for you to use a specific version of the interpreter and a specific package.

To prevent such clutter, developers often create a virtual environment for a project. A virtual environment is a folder that contains a copy (or symlink) of a specific interpreter. When you install into a virtual environment, any packages you install are installed only in that subfolder. When you then run a Python program within that environment, you know that it's running against only those specific packages.

How to create a virtual environment:

  1. Create Virtual Environment

    python -m venv <name_of_envirnment>
    
  2. Activate Virtual Environment

    <name_of_envirnment>\scripts\activate
    

official documentation: Create a virtual environment

JialeDu
  • 6,021
  • 2
  • 5
  • 24