This course runs Python in a browser sandbox. On your computer, the experience is slightly different but the language is identical. You install CPython from python.org, open an interactive interpreter with
>>>, or run scripts directly from a terminal.Installing and the interactive interpreter
Install Python from python.org (on Windows, tick "Add python.exe to PATH"). Then type
python3 in a terminal on macOS or Linux (py on Windows) to open the interactive interpreter. Its >>> prompt runs one line at a time and shows the result straight away, which is the quickest way to try an idea. exit() leaves it.At the >>> prompt
>>> 2 ** 10
1024
>>> name = 'Ada'
>>> name.upper()
'ADA'Scripts and arguments
For anything longer, save your code in a
.py file and run it with python3 hello.py (py hello.py on Windows).# greet.py
import sys
def main():
# argv[0] is the script name, rest are user input
if len(sys.argv) < 2:
return 1
print(f"Hello, {sys.argv[1]}!")
return 0
# On your machine: python3 greet.py Alicesys.argv is the command line split into words. argv[0] is always the path to the running file. The rest are the words you typed after it, in order: the terminal splits on spaces, and quotes keep words together, so python3 greet.py "Ada Lovelace" gives one argument, not two.Exit codes
# Convention: 0 = success
# Any non-zero value signals an error.
import sys
def main():
return 0 # your program's work goes here
code = main()
sys.exit(code)Virtual environments
In a terminal
# Create (on Windows: py -m venv .venv)
python3 -m venv .venv
# Activate (Linux/macOS)
source .venv/bin/activate
# Activate (Windows)
.venv\Scripts\activate
# Inside the venv, python and pip are the venv's own
pip install requestsEach project gets its own
.venv so packages never clash globally. Pin exact versions in requirements.txt for reproducible builds.In a terminal
# save what this project needs
pip freeze > requirements.txt
# on another machine, install exactly that
pip install -r requirements.txtWriting it the way others expect: PEP 8
PEP 8 is Python's style guide, and most Python code you will read follows it:
- Indent with four spaces.
- Name functions and variables in
snake_case, and classes inCapWords. - Keep lines short, around 79 characters.
- Put two blank lines between top-level functions and classes.