Scroll to turn the page
Intro to Programming · Intro to Programming in Python
what a program works with
A program works with values: numbers, text, true and false. In Python every value is an object with a type, and a name (a variable) refers to an object.
score = 42 best = score # best refers to the same 42 score = score + 1 # a new object, 43; best is unchanged name = "Ada" other = name # two names, one string
The figure runs these lines. score = 42 makes an int object 42 and binds the name score to it. best = score binds a second name to the same object: nothing is copied. score = score + 1 computes a new object, 43, and points score at it; best still refers to 42.
That is what = means in Python: assignment binds a name to an object. It never changes the object. Ints and strings can’t be changed at all (they are immutable), so for them the difference rarely shows. It matters for lists (Chapter 4), where two names for one list see each other’s changes.
A name is letters, digits and underscores, not starting with a digit, and case matters (score and Score are different names). Python’s keywords (if, for, def, True …) can’t be names. By convention, names are lowercase with underscores: next_year.
This is the first of seven chapters of a first college programming course (often called CS1), in Python 3: values and types, decisions and loops, functions, lists, dictionaries and files, classes and exceptions, and searching and sorting. Every program on these pages was run in Python 3.13.18, and the figures replay what it did.
the interpreter runs one line at a time
A Python program is a text file of statements. The interpreter (CPython, the standard one) reads the whole file, translates it to bytecode, and runs the statements in order, top to bottom.
Code can be typed into the interpreter one line at a time (the interactive shell, with its >>> prompt), or saved as a .py file and run whole. Anything after a # on a line is a comment, for people; Python ignores it.
Programs go wrong in three ways.
print("start") if price > 10 # missing : print("big") A syntax error breaks the rules of the language. Python finds it while reading the file, before anything runs: this program stops with a SyntaxError on line 2, and even its first line never prints.
price = 12 count = 0 print("price:", price) print("each:", price / count) print("done") price: 12 ZeroDivisionError: division by zero
A run-time error (an exception) happens while the program runs. The figure runs this one: the lines before line 4 run and print, then dividing by zero raises ZeroDivisionError, and the program stops with a traceback naming the line and the error. Line 5 never runs. (Chapter 6 shows how to catch an exception instead.)
a = 7 b = 8 average = a + b / 2 print(average)
11.0 A logic error runs without complaint and gives the wrong answer: the average of 7 and 8 is 7.5, not 11.0. Division comes before addition (page 1.3), so this computed 7 + 4.0. Only testing, running the program on inputs whose answers are known, finds a logic error.
int, float, str, bool and None
Every object has a type, which decides what values it can hold and what can be done with it. type(x) names it.
| type | values | examples |
|---|---|---|
int | whole numbers, of any size | 7, -40, 0 |
float | numbers with a fractional part | 7.0, 2.5, 1e-9 |
str | text: a sequence of characters | "7", 'Ada', "" |
bool | truth values | True, False |
NoneType | one value meaning “nothing” | None |
n = 7 x = 7.0 s = "7" ok = n == x print(type(n), type(x)) print(type(s), type(ok)) print(s == n)
<class 'int'> <class 'float'> <class 'str'> <class 'bool'> False A name has no type of its own; the object it refers to does. Python is dynamically typed: the same name can refer to an int now and a string later, and a type error shows up only when a line runs that can’t work with the type it gets.
n == x compares values: the int 7 equals the float 7.0, so ok is True. But a string is never equal to a number, so s == n is False: "7" is text that happens to look like a number.
From here on, the figure writes small values (numbers, strings, True, None) right in the box of the name that refers to them, as most diagrams do; lists and other objects that can change get boxes and arrows of their own.
/, //, % and **
Python has seven arithmetic operators: +, -, *, / (division), // (floor division), % (remainder) and ** (power).
print(17 / 5) print(17 // 5, 17 % 5) print(-17 // 5, -17 % 5) print(2 ** 10) print(2 + 3 * 4 ** 2)
3.4 3 2 -4 3 1024 50 / always gives a float, even for 6 / 3 (2.0). // counts whole hops: 17 // 5 is 3, and % gives what is left over, 2. Together they always satisfy (a // b) * b + a % b == a.
The figure hops along the number line. Floor division rounds down, toward negative infinity, not toward zero: -17 // 5 is -4 (four hops of 5 to the left reach −20, past −17), and the remainder is 3, the way back up to −17. Java and C would give -3 here; Python keeps the remainder’s sign the same as the divisor’s.
Precedence: ** first, then * / // %, then + -; equal ones go left to right, except **, which goes right to left (2 ** 3 ** 2 is 29 = 512). So 2 + 3 * 4 ** 2 is 2 + 3 × 16 = 50. Parentheses override all of it. A - sign binds more loosely than **: -2 ** 2 is −4.
An int and a float together give a float (1 + 2.0 is 3.0). x += 1 is short for x = x + 1, and the same goes for -=, *=, /=, //=, %= and **=.
close, and exact
A float is stored in 64 bits as a binary fraction (an IEEE 754 double): about 15 to 17 significant digits. Most decimal fractions, like 0.1, have no exact binary form, so a float is the nearest one there is.
total = 0.1 + 0.2 print(total) print(total == 0.3) print(abs(total - 0.3) < 1e-9) print(round(total, 2)) print(2 ** 100)
0.30000000000000004 False True 0.3 1267650600228229401496703205376 The figure adds 0.1 and 0.2 on the number line, then magnifies where the sum lands. Near 0.3 the doubles are 2-54 ≈ 5.55e-17 apart. The real number 0.3 falls between two of them and is stored as the lower, 0.29999999999999998889…; the rounding errors in 0.1 and 0.2 carry the sum to the very next one, 0.30000000000000004440…, which prints as 0.30000000000000004.
So 0.1 + 0.2 == 0.3 is False. Never test floats with ==: test whether they are close (abs(total - 0.3) < 1e-9 is True, as is math.isclose(total, 0.3)), and round only to display: round(total, 2) gives 0.3. (round sends an exact half to the even neighbor: round(2.5), round(3.5) and round(-2.5) are 2, 4, −2.)
Ints have no such limit: Python keeps every digit, however many there are. 2 ** 100 is 1267650600228229401496703205376, exactly. (A float can only get close: 2.0 ** 100 prints as 1.2676506002282294e+30, 17 of those 31 digits.)
characters in order, indexed from both ends
A string (str) is a sequence of characters, written in single or double quotes: 'Ada' and "Ada" are the same string.
word = "Python" print(len(word)) print(word[0], word[-1]) print(word[2] + word[5]) print(word + "!" * 3) word[0] = "J"
6 P n tn Python!!! TypeError: 'str' object does not support item assignment
len(word) is the number of characters, 6. Each character has an index, counted from 0 at the front, so the last is at len(word) - 1. A negative index counts from the back: word[-1] is the last character. word[i] gives a new string of one character (Python has no separate character type).
+ joins two strings (concatenation) and * repeats one: word + "!" * 3 is Python!!! (* first, as in arithmetic). Mixing a string and a number with + is an error: "Age: " + 16 raises a TypeError; convert first, with str(16).
Strings are immutable: no operation changes a string object. The last line tries to, and Python refuses: TypeError: 'str' object does not support item assignment. Every string operation (Chapter 4 has many more) makes a new string instead. An index past the end, such as word[6], raises an IndexError.
input() always gives a string
input(prompt) prints the prompt, waits for the user to type a line and press Enter, and returns what was typed, as a string, without the newline.
age = input("Age? ") print(age + "1") print(int(age) + 1) next_year = int(age) + 1 print("Next year:", next_year) The user typed 16:
Age? 16 161 17 Next year: 17 age refers to the string '16', not the number, so age + "1" joins two strings: 161. To do arithmetic, convert first: int(age) is the int 16, and int(age) + 1 is 17.
| call | gives | example |
|---|---|---|
int(x) | an int | int("16") is 16; int(16.9) is 16 and int(-16.9) is −16 (it drops the fraction) |
float(x) | a float | float("2.5") is 2.5 |
str(x) | a string | str(16) is '16' |
A string that doesn’t look like the number asked for can’t be converted: int("16.5") and int("sixteen") raise a ValueError. A real program checks what the user typed, or catches the error (Chapter 6).
sep, end and format specs
print writes its arguments to the console, separated by a space and followed by a newline. sep= and end= change those two.
name = "Ada" score = 92.456 print(name, score) print(name, score, sep=" | ") print("Hi", end=" ") print(name) print(f"{name} scored {score:.1f}") Ada 92.456 Ada | 92.456 Hi Ada Ada scored 92.5 print(name, score) puts one space between them. With sep=" | ", that string goes between them instead. end=" " ends the line with a space rather than a newline, so the next print continues on the same line: Hi Ada.
An f-string, a string with an f before its opening quote, puts the value of each expression in braces into the text. After a colon comes a format spec: .1f shows a float with one digit after the point, rounded, so 92.456 shows as 92.5.
| f-string | gives |
|---|---|
"{7 / 3:.3f} | 2.333 |
"{1234567:,} | 1,234,567 |
"{0.256:.0%} | 26% |
"{42:5d}| | 42| |
.3f: three digits after the point. ,: commas between thousands. .0%: times 100, as a percent. 5d: an int, 5 characters wide, right-aligned.