1. A program is a recipe
A computer does exactly what it is told, in the order it is told, and nothing else. A program is a list of instructions written in a language the computer's helper (an interpreter) understands. Cooking is a good picture: ingredients (data), steps (instructions), a cook who follows the steps without thinking for themselves.
Python is called an interpreted language, which is a simplification: it first compiles your text to a compact bytecode (the .pyc files in __pycache__), then a virtual machine executes it. You never have to think about the bytecode; you only need to know that an error found while translating (a SyntaxError) stops the program before anything runs, but an error found while running (like dividing by zero) stops it at that exact line.
2. Two ways to run Python
| The REPL (interactive) | A script file | |
|---|---|---|
| Start | python (or py on Windows) | python hello.py |
| Good for | Trying one idea, checking what something does | Real programs you keep and run again |
| Result of each line | Printed immediately | Only what you print() |
| Leave | exit() or Ctrl+Z then Enter (Windows) | Ends by itself |
>>> 2 + 3
5
>>> print("Hello")
Hello
>>> 7 / 2
3.5Try it
3. Your first script
# hello.py
print("Hello, world")
print("Learning Python")C:\> python hello.py Hello, world Learning Python
Three things happened: you saved text in a file; you asked Python to run it; Python executed the two lines in order, top to bottom. print() is a function that writes text to the screen (to stdout, the standard output stream).
Lines starting with # are comments: Python ignores them, humans read them.
Try it
4. Arithmetic: Python as a calculator
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ - * | Add, subtract, multiply | 6 * 7 | 42 |
/ | Division (always a float) | 7 / 2 | 3.5 |
// | Floor division (round down) | 7 // 2 | 3 |
% | Remainder (modulo) | 7 % 2 | 1 |
** | Power | 2 ** 10 | 1024 |
Order of operations is the same as school maths: brackets, then **, then * / // %, then + -. 2 + 3 * 4 is 14, not 20; (2 + 3) * 4 is 20.
Try it
5. What can go wrong in the first five minutes
| Symptom | Cause |
|---|---|
'python' is not recognized | Python is not on your PATH; on Windows try py |
SyntaxError: ... | Python cannot understand the line (missing bracket, quote or colon) |
| Nothing printed | You forgot print() (the REPL shows values, scripts do not) |
| Output from an old version of your file | You did not save it |
NameError | You used a word Python does not know (typo, or defined later) |
Try it
Check yourself
Think first, type an answer if you like, then reveal.