CIS 2020 · Python · Reference
When you install Python from python.org you get more than the language. You get the interpreter, a large standard library of modules, the IDLE editor, the pip package installer, and offline documentation. This page names each piece and shows how to reach it from the keyboard.
One download, several tools. Here is what lands on your machine.
py launcher for picking between installed versions. Every tool with a -m line above is really a module you run as a program, which is a pattern worth remembering.The program that reads your Python and carries it out. Everything else is built around it.
Open a terminal. On Windows that is Command Prompt or PowerShell; on macOS it is Terminal. Then start Python:
# Windows py # or python # macOS python3
You now see the >>> prompt. This is the interactive shell: type an expression, press Enter, see the result. Type exit() or press Ctrl+Z then Enter (Windows) or Ctrl+D (macOS) to leave.
To run a program you saved in a file, pass the file name instead:
# Windows python hello.py # macOS python3 hello.py
Two checks that are always useful:
python --version # which version am I running Python 3.12.4 # inside the >>> shell: where is this interpreter, and # which folders does it search when I import something >>> import sys >>> sys.executable 'C:\\Users\\you\\AppData\\Local\\Programs\\Python\\Python312\\python.exe' >>> sys.path ['', 'C:\\...\\python312.zip', 'C:\\...\\Lib', 'C:\\...\\site-packages']
From the terminal you can also ask the operating system: where python on Windows, which python3 on macOS.
A module is a file of ready made code. The standard library is the big set of modules that comes with Python, so you can use them without installing anything.
You bring a module in with import, then reach into it with a dot:
>>> import math >>> math.sqrt(2) 1.4142135623730951 >>> math.pi 3.141592653589793 >>> from random import randint >>> randint(1, 6) 4 >>> import statistics >>> statistics.mean([3, 5, 7, 9]) 6
To see what is inside a module, or read its documentation:
>>> import math >>> dir(math) # every name the module provides ['acos', 'acosh', ..., 'sqrt', 'tan', 'tau', 'trunc'] >>> help(math) # the full manual page for the module >>> help(math.sqrt) # just one function >>> import random >>> random.__file__ # where the module file lives on disk 'C:\\...\\Python312\\Lib\\random.py'
A few modules such as sys and math are compiled into the interpreter itself and have no .py file, so sys.__file__ does not exist. You can see that group with sys.builtin_module_names.
| Module | What it gives you |
|---|---|
| math | square roots, pi, trigonometry, careful rounding |
| random | random numbers, shuffles, random choices |
| statistics | mean, median, standard deviation |
| datetime | dates, times, and the gap between two of them |
| os | files, folders, and environment settings |
| sys | the interpreter itself: version, arguments, import paths |
| json | read and write JSON text |
| csv | read and write spreadsheet style files |
| tkinter | build desktop windows and buttons (IDLE is written with it) |
| turtle | simple drawing, good for a first graphics program |
| pathlib | a cleaner way to work with file paths |
| sqlite3 | a small SQL database with nothing to install |
IDLE stands for Integrated Development and Learning Environment. It is the small editor that ships with Python, and it is what we use in CIS 2020.
It is itself a Python program, written with the tkinter module, so it looks the same on Windows and macOS.
Opening it:
py -m idlelibpython3 -m idlelibThe two windows:
>>> prompt as the interpreter, good for trying one line at a time..py name, then press F5 to run it. The Shell shows the output and restarts fresh each run.Useful settings live under Options, Configure IDLE: turn on line numbers, set the font size, and change indentation width.
Keywords are the words that are part of Python's grammar, such as if, for, and def. You cannot use them as variable names. Modern Python 3 has 35 of them, though the exact count has shifted across versions, so check rather than memorize.
The quickest look, from the >>> prompt:
>>> help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more help.
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
The keyword module gives you the same information as data you can test against:
>>> import keyword >>> keyword.kwlist ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] >>> len(keyword.kwlist) 35 >>> keyword.iskeyword("for") True >>> keyword.iskeyword("range") False >>> keyword.softkwlist # words reserved only in certain places ['_', 'case', 'match', 'type']
These are the functions you can call without importing anything: print, len, range, input, int, float, str, type, abs, round, sum, min, max, sorted, and more.
They live in a module called builtins that Python imports for you automatically every time it starts. To see the whole set:
>>> dir(__builtins__) # every name that is always available ['ArithmeticError', ..., 'abs', 'aiter', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', ..., 'print', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'str', 'sum', 'tuple', 'type', 'vars', 'zip'] >>> help("builtins") # the manual: functions, types, and exceptions
That list also contains the built in types (int, str, list) and every exception name. The clean list of just the functions, about seventy of them, is in the documentation under Built in Functions at docs.python.org.
A keyword is part of the language grammar. It is a fixed list and you can never use it as a name. A built in function is just a name Python defines for you. You can reassign it, which is exactly the problem: writing list = [1, 2, 3] is legal and then list(...) stops working. That is why you avoid naming variables list, str, sum, type, or input.
pip is the tool that installs packages other people have written. The standard library is large, but pip reaches the roughly half a million extra packages on PyPI, the Python Package Index, such as requests, pandas, and matplotlib.
The name is a short joke on "pip installs packages". It has come bundled with Python since version 3.4, so if you have Python you have pip.
# Windows py -m pip --version # macOS python3 -m pip --version
The safest way to call pip is py -m pip on Windows or python3 -m pip on macOS. Writing it that way runs pip with the exact interpreter you named, so packages land where you expect. A bare pip command can point at a different Python than the one you are using.
Put py -m (Windows) or python3 -m (macOS) in front of each of these:
pip install requests # install the newest version pip install pandas==2.2.2 # install one exact version pip install --upgrade requests # move a package up to the newest pip install --upgrade pip # update pip itself pip list # everything installed right now pip show requests # version, location, dependencies pip uninstall requests # remove a package pip install -r requirements.txt # install a project's whole list
| Task | Windows | macOS |
|---|---|---|
| Start Python | py | python3 |
| Check the version | python --version | python3 --version |
| Check pip | py -m pip --version | python3 -m pip --version |
| Install a package | py -m pip install requests | python3 -m pip install requests |
| List packages | py -m pip list | python3 -m pip list |
| Uninstall | py -m pip uninstall requests | python3 -m pip uninstall requests |
On macOS, never run sudo pip. If you get a permissions error, add --user to the install command, or better, use a virtual environment.
Use one virtual environment per project so packages for different projects do not collide. This site is built inside one.
# Windows py -m venv venv venv\Scripts\activate # macOS python3 -m venv venv source venv/bin/activate
Once it is active, pip install puts packages in that folder only. Type deactivate to leave it.
Start the interpreter and paste these one at a time.
import sys; print(sys.version) # your exact Python build import keyword; print(keyword.kwlist) # the reserved words print(dir(__builtins__)) # the always available names import this # the Zen of Python, an easter egg module help() # interactive help; type quit to leave