CIS 2020 · Python · Reference

What Python installs

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.

The pieces

One download, several tools. Here is what lands on your machine.

The parts of a Python installation A container labelled "what the python.org installer puts on your machine" holds six tiles: the interpreter, the standard library, IDLE, pip, venv, and help with documentation. What the python.org installer puts on your machine one download, several tools Interpreter python on Windows python3 on macOS gives you the >>> prompt and runs your .py files Standard library hundreds of modules you import, for example: math random os sys json datetime csv statistics tkinter IDLE a simple editor and interactive shell, bundled in what we use in CIS 2020 pip installs extra packages from PyPI, the Python Package Index py -m pip install ... venv makes an isolated set of packages for one project python -m venv venv help() and docs offline documentation, plus help() and dir() at the prompt no internet needed
Windows also gets the 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 interpreter

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.

The standard library and modules

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.

Modules you will meet early

A small sample. The full list is at docs.python.org under "The Python Standard Library".
ModuleWhat it gives you
mathsquare roots, pi, trigonometry, careful rounding
randomrandom numbers, shuffles, random choices
statisticsmean, median, standard deviation
datetimedates, times, and the gap between two of them
osfiles, folders, and environment settings
systhe interpreter itself: version, arguments, import paths
jsonread and write JSON text
csvread and write spreadsheet style files
tkinterbuild desktop windows and buttons (IDLE is written with it)
turtlesimple drawing, good for a first graphics program
pathliba cleaner way to work with file paths
sqlite3a small SQL database with nothing to install

IDLE

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:

The two windows:

Useful settings live under Options, Configure IDLE: turn on line numbers, set the font size, and change indentation width.

Reserved words (keywords)

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']

Built in functions

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.

Keyword or built in function?

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

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.

Check that it is there

# 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.

The commands you will use

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

Windows and macOS, side by side

The only real difference is the interpreter name.
TaskWindowsmacOS
Start Pythonpypython3
Check the versionpython --versionpython3 --version
Check pippy -m pip --versionpython3 -m pip --version
Install a packagepy -m pip install requestspython3 -m pip install requests
List packagespy -m pip listpython3 -m pip list
Uninstallpy -m pip uninstall requestspython3 -m pip uninstall requests

Two habits that save trouble

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.

Try these now

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