Put things in boxes first, then let the program decide: Python variables, data types, and control flow
Variables are boxes for things, lists and dicts are boxes for lots of things, and if, for, and while let a program decide and repeat work on its own. Following Chapters 3-5 of the official Python Tutorial: division and the float quirk, string indexing and slicing, list assignment that never copies, dict get vs KeyError, truthiness, if/elif/else, for and range, while with break/continue/loop-else — plus a 100-accident breakdown from a fictional bookstore script.

First, the boundaries of this guide. This is the first guide in a new "Python Basics" series on this site, and it is about the Python language itself: how to store things in variables, the rules for numbers and text, how to hold a bunch of things in lists and dictionaries, and how to make a program decide things and repeat work. It does not overlap with the site's existing JavaScript series: timers, the event loop, generators, and Web Workers over there are all about JavaScript in the browser; this one is about Python in the Python interpreter, and the two languages are written differently and play by different rules. The running example below, "Morning Light Bookstore", is a fictional practice project: a small neighborhood bookstore whose owner wants a little Python script to keep the books, work out prices, count what is left in stock, and apply discounts. Every operation, code sample, and number built around it was made up to explain how things work; none of it is a real record. Every statement about Python syntax and behavior comes from three chapters of the official Python Tutorial: "An Informal Introduction to Python" (Chapter 3), "More Control Flow Tools" (Chapter 4), and "Data Structures" (Chapter 5). Sources are listed in each guide's meta information and evidence record. By the end of this guide you should be able to do four things: store numbers, text, and lists in variables; know the rules for numbers and strings; hold a bunch of related data in lists and dictionaries; and use if, for, and while to let a program decide things and repeat work on its own. Next time we will pack repeated work into functions and split files into modules.
Step 1: Get running: say hello in the interpreter
Python does not need to be compiled before it runs. It has an "interpreter": you type a line, it works it out, and it answers right away. Once Python is installed, type python3 in a terminal; when you see the >>> prompt, the interpreter is waiting for you. Say hello first:
>>> print('Hello, Morning Light Bookstore')
Hello, Morning Light Bookstore
>>> print('Sold', 3, 'books today')
Sold 3 books today
print() is a built-in function: whatever you put in the parentheses, it prints without the quotes, and when you give it several things it puts a space between them. Anything after a # is a comment: the interpreter skips it; it is only there for people to read:
>>> # the line below works out today's first sale
>>> 39.5 + 29.0
68.5
Working things out is not enough; what you work out needs somewhere to live. That somewhere is called a "variable", written as a name, an equals sign, and a value:
>>> price = 39.5
>>> count = 3
>>> price * count
118.5
price = 39.5 means: hand the number 39.5 to the name price to look after, and from now on writing price means 39.5. The equals sign here does not mean "is equal to" the way it does in maths; it means "hand over". That matters later, because it looks a lot like the comparison operator == but does a different job. If you use a name that has never been given anything, the interpreter complains straight away and tells you the name is not defined:
>>> total
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'total' is not defined
Seeing a NameError is no cause for alarm: it is only saying it does not know this name — you either have not assigned it yet, or you misspelled it. My judgment is this: in your first few days with Python, build two habits — give variables names that say what they are, price rather than p1; and print out an intermediate result to look at it before moving on. Neither habit costs any time, and together they save about half the time you would spend hunting for mistakes.
Step 2: Numbers can calculate, but learn four kinds of division and one float quirk first
The interpreter starts out as a calculator. Whole numbers are int, numbers with a decimal point are float, and the arithmetic signs are the same as in school, with parentheses for grouping:
>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5 # division always returns a floating-point number
1.6
Look at the third line: (50 - 5*6) / 4 gives 5.0, not 5. The official docs say it plainly: division (/) always returns a float. For a whole-number result, use floor division //; for the remainder, use %; for powers, use **:
>>> 17 / 3 # classic division
5.666666666666667
>>> 17 // 3 # floor division discards the fractional part
5
>>> 17 % 3 # the % operator returns the remainder
2
>>> 5 * 3 + 2 # floored quotient * divisor + remainder = 17
17
>>> 5 ** 2 # 5 squared
25
>>> 2 ** 7 # 2 to the power of 7
128
When integers and floats are mixed in one calculation, the integer is first converted to a float, and the result is a float: 4 * 3.75 - 1 gives 14.0. The docs have a tax example that works nicely for the bookstore's books: a book costs 100.50, the tax rate is 12.5%; work out the tax, then the price with tax, then round to two decimal places:
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + 12.5625
113.0625
>>> round(113.0625, 2)
113.06
The second argument of round() is how many decimal places to keep. There is one small trap beginners often hit here: floats are stored in the computer as binary approximations, so 0.1 + 0.2 is not exactly 0.3; it is 0.30000000000000004. That is not a Python bug; nearly every language does the same thing. My judgment is: when you work with money, do not compare floats for equality directly — either round to two decimals first and then compare, or count money in cents with integers. In the bookstore example, 39.5 yuan is 3950 cents, and integer arithmetic never grows a tail like that.
Step 3: Strings: text is text, numbers are numbers
Text in Python is called str, wrapped in single or double quotes with the same result. Digits inside quotes are still text, not numbers:
>>> 'spam eggs' # single quotes
'spam eggs'
>>> "Paris rabbit got your back :)! Yay!" # double quotes
'Paris rabbit got your back :)! Yay!'
>>> '1975' # digits in quotes are still a string
'1975'
To write a single quote inside a single-quoted string, either escape it with a backslash or switch to double quotes around it:
>>> 'doesn\'t' # use \' to escape the single quote...
"doesn't"
>>> "doesn't" # ...or use double quotes instead
"doesn't"
The backslash does other things too: \n is a newline, \t is a tab. print() really interprets them, while looking at a string directly shows it with the backslashes still in place:
>>> s = 'First line.\nSecond line.'
>>> s
'First line.\nSecond line.'
>>> print(s)
First line.
Second line.
If you want backslashes to stay exactly as they are — for a Windows path, say — put an r before the quote to make a "raw string": print(r'C:\this\name') prints C:\this\name unchanged, while the version without r turns \t into a tab and \n into a newline. Triple quotes ("""...""") let a string run over several lines, which suits multi-line notes.
Strings can be glued together, and repeated:
>>> 3 * 'un' + 'ium'
'unununium'
>>> 'Py' 'thon'
'Python'
Note the second line: two string literals sitting next to each other are joined automatically — but that only works for literals. A variable next to a literal is a syntax error; to join a variable and a string, use +: prefix + 'thon', where prefix = 'Py'.
Strings can also be picked apart by position, which is called "indexing" and "slicing". The first character is at position 0, not 1; negative numbers count back from the right:
>>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'
>>> word[-1] # last character
'n'
>>> word[-2] # second-last character
'o'
>>> word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'
The rule for slices is "start included, end excluded": leave the start out and it starts from the beginning; leave the end out and it runs to the end. So word[:2] is 'Py' and word[4:] is 'on'. The rule has a nice property: word[:2] + word[2:] is always the original word again — cut it apart and join it back, and nothing is lost. An index that is too large is an error, but a slice that is too large is handled gracefully:
>>> word[42] # the word only has 6 characters
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> word[4:42] # slicing past the end just gives what is there
'on'
>>> word[42:]
''
Python strings are "immutable": you cannot change one character in place. If you want a different string, build a new one:
>>> word[0] = 'J'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'
Finally, remember the built-in len(), which counts how long a string is: len('supercalifragilisticexpialidocious') is 34. It comes in handy at the bookstore: before cutting a book title short for display, count it with len() first.
Step 4: Lists: one box holding a bunch of things
One book's price fits in one variable, but a whole shelf of books needs a box to hold them. That box is called a "list", written with square brackets and commas between the items. Lists usually hold items of the same kind, but mixing types does not raise an error:
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]
Like strings, lists can be indexed and sliced, and slicing returns a new list:
>>> squares[0] # indexing returns the item
1
>>> squares[-1] # the last item
25
>>> squares[-3:] # slicing returns a new list
[9, 16, 25]
>>> squares + [36, 49, 64, 81, 100] # concatenation
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Unlike strings, lists are "mutable": their contents can be changed in place, and items can be added. The docs have an example that fixes a mistake — the cube of 4 was written as 65 instead of 64 — then adds the cubes of 6 and 7:
>>> cubes = [1, 8, 27, 65, 125] # something's wrong here: 4 cubed is 64, not 65
>>> 4 ** 3
64
>>> cubes[3] = 64 # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]
>>> cubes.append(216) # add the cube of 6
>>> cubes.append(7 ** 3) # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]
append() is a method of the list, written as list.method(): the thing before the dot is the object, and the thing after the dot is the job it does. Lists have more methods. The useful ones are extend() (append every item from another iterable), insert() (insert at a given position), remove() (remove the first item equal to the value), pop() (take the item at a given position and return it; with no position it takes the last), clear() (remove all items), index() (find a value's position), count() (count how many times a value appears), sort() (sort in place), reverse() (reverse in place), and copy() (return a shallow copy). The docs' example:
>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4) # Find next banana starting at position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'
Two things to note. First, methods that only modify the list and return nothing — insert, remove, sort — return None; do not expect fruits.sort() to hand you a sorted new list, because it sorts the original in place. Second, not everything can be sorted: [None, 'hello', 10] cannot be sorted, because integers cannot be compared to strings and None cannot be compared to other types, so it raises a TypeError. The docs state this as a design principle for all mutable data structures in Python: methods that only modify return None.
Lists have one more trap that catches nearly every beginner: simple assignment never copies data. Assign a list to another variable and both names point at the same box; change it through one name and the other name sees the change:
>>> rgb = ["Red", "Green", "Blue"]
>>> rgba = rgb
>>> id(rgb) == id(rgba) # they reference the same object
True
>>> rgba.append("Alph")
>>> rgb
["Red", "Green", "Blue", "Alph"]
For a real copy, slice the whole list with [:] or call copy(): the slice is a new box, and changing it leaves the original alone:
>>> correct_rgba = rgba[:]
>>> correct_rgba[-1] = "Alpha"
>>> correct_rgba
["Red", "Green", "Blue", "Alpha"]
>>> rgba
["Red", "Green", "Blue", "Alph"]
Slices can also replace a stretch, remove a stretch, or clear the whole list. Replace a stretch with new values to change it; replace it with an empty list to delete it; replace the whole list with an empty list to clear it:
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters[2:5] = ['C', 'D', 'E'] # replace some values
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> letters[2:5] = [] # now remove them
>>> letters
['a', 'b', 'f', 'g']
>>> letters[:] = [] # clear the list
>>> letters
[]
Lists can be nested, too: x = [['a', 'b', 'c'], [1, 2, 3]], where x[0] is ['a', 'b', 'c'] and x[0][1] is 'b'. The bookstore's list of books could be built that way — each book a small list, the shelf a big list of small lists. But then you would have to remember by heart that position 0 is the title and position 1 is the price, which is easy to get wrong. The next step has a better way to hold a book.
Step 5: Dictionaries: find things by name, not by counting positions
A list finds things by position: to get the third book you count to 2. A dictionary finds things by name: a set of "key: value" pairs, where the key is the name and the value is the thing. A phone book is a dictionary: names are keys, numbers are values. The docs' example:
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127 # add one pair
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}
>>> tel['jack'] # look a value up by its key
4098
Keys must be unique within one dictionary: storing a value under a key that is already in use forgets the old value. Keys can be any immutable type; strings and numbers can always be keys. Lists cannot be keys, because a list can be changed in place, and then it could not be found again. Asking for a key that is not there with subscripting raises a KeyError:
>>> tel['irv']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'irv'
If you do not want a missing key to crash the program, use get(): it returns the value when the key is there, and None — or a default you choose — when it is not:
>>> print(tel.get('irv'))
None
>>> tel.get('irv', 0)
0
Delete a pair with del; test whether a key is there with in; list(d) lists all the keys in the order they were inserted; sorted(d) lists them sorted:
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}
>>> list(tel)
['jack', 'guido', 'irv']
>>> sorted(tel)
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False
Dictionaries can also be built with the dict() constructor from a sequence of key-value pairs, with a "dict comprehension" that computes them, or by merging two dictionaries with **:
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
>>> {**{'a': 1}, **{'b': 2}}
{'a': 1, 'b': 2}
Back at the bookstore: holding a book as a dictionary is much clearer, because the title, price, and stock each have their own key and nobody has to remember positions:
>>> book = {'title': 'The Three-Body Problem', 'price': 59.0, 'stock': 7}
>>> book['price']
59.0
>>> book['stock'] = 6 # sold one copy, stock down by one
>>> book
{'title': 'The Three-Body Problem', 'price': 59.0, 'stock': 6}
My judgment is: three rules are enough for beginners — lists go by position, dictionaries go by name; before changing data, decide whether you need a copy; and before taking a value out of a dictionary, ask whether the key is there — use brackets when it is, and get() with a default when it might not be. Those three rules block most list and dictionary accidents.
Step 6: Truth and comparison: teach the program to tell right from wrong
Before a program can decide anything, it has to be able to judge whether a statement is true or false. Comparison operators are written the same as in C: < less than, > greater than, == equal to, <= less than or equal to, >= greater than or equal to, and != not equal to. The docs' Fibonacci example already uses one: while a < 10 keeps looping as long as a is less than 10.
Comparisons can be chained: a < b == c tests whether a is less than b and moreover b equals c. Sequences compare lexicographically, item by item:
>>> (1, 2, 3) < (1, 2, 4)
True
>>> [1, 2, 3] < [1, 2, 4]
True
>>> 'ABC' < 'C' < 'Pascal' < 'Python'
True
But comparing objects of different types with < raises an error: 3 < 'a' raises a TypeError, because an integer and a string have no agreed order. The docs say it plainly: rather than providing an arbitrary ordering, the interpreter raises a TypeError.
Judgments can be combined: and means "and also", or means "or else", not negates. The Boolean operators and and or are "short-circuit" operators: they evaluate from left to right and stop as soon as the outcome is determined. In A and B and C, if B is false, C is never evaluated. There is one more thing people miss: when used as a general value rather than a Boolean, a short-circuit operator returns the last evaluated argument itself, not True or False:
>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'
The empty string is the first value, but it is "false", so or keeps looking and finds 'Trondheim'. That is the other half of what "true and false" means in Python: it is not only True and False that count — any non-zero integer value is true and zero is false; anything with a non-zero length is true and empty sequences are false:
>>> bool(0)
False
>>> bool(3)
True
>>> bool('')
False
>>> bool([])
False
>>> bool([0])
True
Note the last line: [0] holds a zero, but the list itself is not empty, so it is true. Do not mix up "the thing inside the list is true or false" with "the list itself is empty or not". Two more operators: in asks "is it inside?", and is asks "is it the very same object?" — the id(rgb) == id(rgba) test in Step 4 was asking the second question. One more thing to mention: in Python, unlike C, assignment inside expressions must be done explicitly with the "walrus operator" := — (n := 6) hands 6 to n and keeps calculating. That avoids the classic C mistake of typing = in an expression when == was intended.
Step 7: if: speaking in cases
Once a program can judge true and false, it can speak in cases. An if statement is written as if, a condition, and a colon, with the work to do when the condition holds indented four spaces on the next line. For another case, use elif; for what to do when no condition holds, use else. There can be zero or more elif parts, and the else part is optional. The docs' example sorts a number into a category:
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
... x = 0
... print('Negative changed to zero')
... elif x == 0:
... print('Zero')
... elif x == 1:
... print('Single')
... else:
... print('More')
...
More
With 42 as the input, the first three conditions all fail and the code falls through to else, printing More. The same code prints Negative changed to zero for -3, Zero for 0, and Single for 1. One detail matters here: int(input(...)) turns what the person typed into an integer before comparing — input() always returns a string, and comparing a string directly with a number raises a TypeError, as Step 3 explained.
The bookstore version: label a book by how much stock is left:
>>> stock = 0
>>> if stock == 0:
... print('Out of stock, time to reorder')
... elif stock < 5:
... print('Only a few copies left')
... else:
... print('Enough in stock')
...
Out of stock, time to reorder
The colon and the indentation are how Python groups statements: the colon says "the lines below belong together", and the indentation says "this group ends here". Every line in one basic block must be indented by the same amount. The docs' style advice is four-space indentation and no tabs. My judgment is: most indentation mistakes in the first weeks are not "not knowing how to indent" — they are mixing spaces and tabs, or pasting in code with different indentation. Ask your editor to show invisible characters, or simply use four spaces everywhere, and most of the trouble goes away.
One more thing to mention: to compare the same value against several constants, the match statement can do the job too. It is the "pattern matching" added in Python 3.10: it matches literals, tuples, dictionaries, and classes, and only the first pattern that matches gets executed. This guide will not go into it; knowing it exists and coming back to it when you write a multi-way branch is enough for now.
Step 8: for and range: one at a time
The bookstore has dozens of books; writing a print() for each one by hand is not realistic. A for loop is "one at a time": it takes each item of a sequence in turn and does the same thing with it. Python's for differs a bit from what you may be used to in C or Pascal: rather than always iterating over an arithmetic progression of numbers, it iterates over the items of any sequence, in the order they appear:
>>> words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print(w, len(w))
...
cat 3
window 6
defenestrate 12
When you do need to iterate over numbers, the built-in range() comes in handy. Note that the given end point is never part of the generated sequence: range(10) generates 10 values, the legal indices for a sequence of length 10:
>>> for i in range(5):
... print(i)
...
0
1
2
3
4
>>> list(range(5, 10))
[5, 6, 7, 8, 9]
>>> list(range(0, 10, 3))
[0, 3, 6, 9]
>>> list(range(-10, -100, -30))
[-10, -40, -70]
>>> sum(range(4)) # 0 + 1 + 2 + 3
6
range(5, 10) starts at 5 and stops before 10; range(0, 10, 3) steps by 3; the step can even be negative. Printing a range shows range(0, 10): it is not a list, just an object that returns successive items when you iterate over it, without really making the list — which saves space. The docs call such an object "iterable". To turn it into a real list, wrap it in list().
Loops often need the position and the value at the same time: use enumerate(). To loop over two sequences at once, pair them with zip(). To go in reverse, call reversed(). To go in sorted order, use sorted(), which returns a new sorted list and leaves the source unaltered. To loop over unique elements in sorted order, combine sorted() with set():
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print(i, v)
...
0 tic
1 tac
2 toe
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
... print(f)
...
apple
banana
orange
pear
One more warning the docs call out: code that modifies a collection while iterating over it can be tricky to get right. It is usually more straightforward to loop over a copy of the collection, or to create a new collection:
>>> users = {'Hans': 'active', 'Éléonore': 'inactive', 'Taro': 'active'}
>>> for user, status in users.copy().items():
... if status == 'inactive':
... del users[user]
>>> users
{'Hans': 'active', 'Taro': 'active'}
The bookstore version: hold the three books in a list, each one a dictionary, and one loop works out the total value of the stock and picks out what is still available:
>>> books = [
... {'title': 'Twenty Thousand Leagues Under the Sea', 'price': 39.5, 'stock': 12},
... {'title': 'The Little Prince', 'price': 29.0, 'stock': 0},
... {'title': 'The Three-Body Problem', 'price': 59.0, 'stock': 7},
... ]
>>> in_stock = [bk['title'] for bk in books if bk['stock'] > 0]
>>> in_stock
['Twenty Thousand Leagues Under the Sea', 'The Three-Body Problem']
>>> total = sum(bk['price'] * bk['stock'] for bk in books)
>>> round(total, 2)
887.0
The total stock value is 887.0: 39.5 times 12 is 474.0, 59.0 times 7 is 413.0, and together they make 887.0. The square brackets with a for inside in the first line are a "list comprehension", the shorthand Chapter 5 teaches: first say what you want, then where it comes from and what condition it must meet. It means exactly the same as building an empty list and appending inside a loop, only shorter.
Step 9: while, break, continue: three ways to stop a loop, and one placeholder
A for loop is "go through these one by one"; a while loop is "keep going as long as the condition is still true". The docs' Fibonacci example is the classic while:
>>> a, b = 0, 1
>>> while a < 10:
... print(a)
... a, b = b, a+b
...
0
1
1
2
3
5
8
The first line is a "multiple assignment": a and b get 0 and 1 at the same time; the last line does the same, with the right-hand side evaluated first before any assignment takes place. The loop runs while a < 10 and stops when a reaches 10. The keyword argument end can change what print() puts at the end of its output: print(a, end=',') prints everything on one line, 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,.
What while fears most is a condition that never becomes false: forget to update the condition and the loop never stops. That is the ninth category of accident in the chart below. The two brakes are break and continue: break breaks out of the innermost enclosing loop, and continue continues with the next iteration:
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(f"{n} equals {x} * {n//x}")
... break
...
4 equals 2 * 2
6 equals 2 * 3
8 equals 2 * 4
9 equals 3 * 3
>>> for num in range(2, 10):
... if num % 2 == 0:
... print(f"Found an even number {num}")
... continue
... print(f"Found an odd number {num}")
...
Found an even number 2
Found an odd number 3
Found an even number 4
Found an odd number 5
Found an even number 6
Found an odd number 7
Found an even number 8
Found an odd number 9
In the first example, break jumps out of the inner loop as soon as a factor is found, so each composite number prints only its first factor. In the second, an even number is printed and then continue skips the "found an odd number" line below, so each number appears exactly once.
A loop can also take an else clause: if the loop finishes without executing a break, the else clause executes; if the loop was terminated by a break, it does not. Searching for primes shows it best:
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
Note that the else belongs to the for loop, not the if statement — the indentation shows it. The docs suggest thinking of it like the else of a try statement: a try statement's else runs when no exception occurs, and a loop's else runs when no break occurs.
Finally, pass: it does nothing, and it is used when a statement is required syntactically but the program requires no action. It works as a placeholder for a function or conditional body while you are still working on the code:
>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
...
>>> def initlog(*args):
... pass # Remember to implement this!
...
Step 10: Count the seven most common beginner accidents, then keep going
The chart below breaks down 100 accidents from the fictional Morning Light Bookstore script in its first month of learning Python, by cause. The numbers are made up to show the distribution, but every category is a real trap covered in the nine steps above:
The top three add up to 58, and all three come from writing Python like another language: forgetting the colon, because other languages group code with braces while Python uses colons plus indentation; misaligned indentation, because in other languages indentation is only cosmetic while in Python it is the grouping itself; and writing = as ==, because in other languages the two look alike too — but in Python one means "hand over" and the other means "compare". The fourth category is adding a number to a string directly: Python will not quietly turn the number into text for you — 39.5 + 'yuan' raises a TypeError right away, so convert with str() first, or use an f-string. The fifth, an index out of range, and the seventh, a missing dict key, were both covered earlier: a slice past the end is fine, an index past the end is an error, and get() is the safe way to read a dict. The sixth is a while loop that never updates its condition and never stops: when you write a while, decide first what will make it stop, then write the body.
By now the bookstore's script can run: the books live in a list, each book is a dictionary, one loop works out the total stock value of 887.0, and books over 50 get 10% off — The Three-Body Problem at 59.0 becomes 53.1 after the discount, while Twenty Thousand Leagues Under the Sea at 39.5 is under 50 and stays full price. Next time we will pack these scattered steps into functions: the discount rule becomes one function, checkout becomes another, and then the functions will be split into files that can import each other. Everything written in this first guide will still be there — just living in a tidier house.
Comments (0)
Sources
Related articles
An exception is not a broken program: it is Python telling you what went wrong, with a name you can catch. Following Chapter 8 of the official Python Tutorial: syntax errors vs exceptions, try/except, matching by inheritance, which errors to catch and which to leave alone, raise, else, finally, with, user-defined exceptions, chaining, and ExceptionGroup — plus a 100-accident breakdown from a fictional bookstore script.
A class bundles data and its rules together: one Book class gives every book its own state, methods let objects do the work themselves, and inheritance lets an e-book stand on a paper book's shoulders. Following Chapter 9 of the official Python Tutorial: class and __init__, self, methods, class vs instance variables, attribute lookup, inheritance and overriding, super(), the underscore-private convention, dataclasses, __iter__ and __next__ — plus a 100-accident chart.
A function packs repeated work into a name; a module packs definitions into a file you take out with import. Following Chapter 4 sections 4.8-4.9 and Chapter 6 of the official Python Tutorial: def and return, local and global scope, defaults evaluated once, keyword arguments, *args and **kwargs, / and *, lambda, docstrings and annotations, the ways to import, the __main__ guard, packages and the search path — plus a 100-accident breakdown from a fictional bookstore script.