Notebook commands (%pip, !ls)
A line starting with % or ! in a cell is not Python: it is an instruction for the notebook or for the terminal.
Used in 116 lessons of the course, from 00.02.
Jupyter and IPython understand two special prefixes at the start of a line.
%is a magic command: an instruction for the notebook itself, like%pip --version.!runs the line in the system terminal, like!ls.
Plain Python knows neither. IPython, the notebook's engine, recognizes them before Python ever sees the code. That is why the same line fails with SyntaxError in a .py file.
Why %pip and not !pip: %pip installs into the same environment the notebook's kernel uses. !pip may point to a different Python and leave you with a package installed where you can't see it.
In the course you will see %pip at the top of almost every lesson, to install or check packages before importing them. Put it in its own cell, above the import lines.
Reach for it when: you need to install a package or run a terminal command without leaving the notebook. Use it only in notebooks, never in `.py` files.
Examples
Common mistake
%pip --version
Why: A `.py` file is read by Python directly, and `%pip` is not Python syntax. Only IPython understands it.
How to write it: Run it in a notebook cell, or in the terminal type pip --version without the %.
Common mistake
!ls
Why: The `!` is also an IPython feature. Outside the notebook, Python does not know what to do with it.
How to write it: In a script use subprocess.run(["ls"]), or type ls directly in the terminal.
