How to fix pip install invalid syntax error

When installing a Python package, you might get an error as follows:

>>> pip install numpy
SyntaxError: invalid syntax

This error occurs when you run the pip install command from the Python shell and not the terminal.

The Python shell is an environment to run Python code. Usually, you open the shell by running the python or python3 command from the terminal:

python
Python 3.11.3 (main, Apr  7 2023, 20:13:31) 
[Clang 14.0.0 (clang-1400.0.29.202)] 
on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 

The three arrows >>> is an indicator that you’re inside a Python shell. When you run a pip install command from this place, you’ll get the invalid syntax error:

>>> pip install pandas
SyntaxError: invalid syntax

To resolve this error, you need to exit the shell by running the exit() function:

>>> exit()

The terminal will shut the Python shell, and you should be able to run the pip install command without receiving the error:

pip install numpy  
Collecting numpy
...
Installing collected packages: numpy
Successfully installed numpy-1.24.3

If pip install doesn’t work, run the command under the python command as follows:

python -m pip install numpy

# or
python3 -m pip install numpy

You can’t run the pip install command under the Python shell. The command can only be executed from the command line.

I hope this tutorial helps. Happy coding! 👍

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.