Learnings

Python basics, part 3 of 6

Python Loops

A loop runs the same statements again and again, either once for each item in a collection or for as long as a condition stays true. This page is a rewrite of the first Pythofrank lesson from February 2017. The original examples are kept, updated from Python 2.7 to Python 3 and split into short chapters, with a few new ones added.

Counting with range

A for loop takes items one at a time from whatever follows in. range(start, stop) supplies whole numbers from start up to, but not including, stop.

Concept: print() ends with a new line by default. end=" " replaces that new line with a space, so the numbers stay on one row.

A loop inside a loop

The inner loop runs completely for every single step of the outer loop. That is exactly the shape of a multiplication table: one row per number, ten columns in each row.

Concept: {i * j:4} inside an f-string pads the number to 4 characters, which keeps the columns straight.

Looping over a string

A string is a sequence of characters, so a for loop hands them over one by one.

Looping over a list

Name the loop variable after one item of the list. for city in cities reads like a sentence.

Position and item with enumerate

When you also need to know which item you are on, do not keep a counter by hand. enumerate() gives the position and the item together.

Looping over a dictionary

A dictionary stores key and value pairs. Looping over it directly gives the keys. .items() gives each key with its value.

Concept: inside brackets or braces a statement can run over several lines, so no \ is needed at the end of each line.

Two lists at once with zip

zip() pairs the first items of both lists, then the second items, and so on. It stops when the shorter list runs out.

while: loop until a condition changes

Use for when you know what you are looping over. Use while when you only know when to stop. Something inside the loop must eventually make the condition false, or it never ends.

break and continue

continue skips the rest of this round and moves on to the next item. break leaves the loop completely.

A loop that builds a list

Building a new list from an old one is so common that Python has a one-line form for it, called a list comprehension.

What changed since Python 2

The original lesson was written for Python 2.7, which reached its end of life in 2020. If you meet old code, these are the differences that matter for loops.

Python 2.7 (2017 lesson)Python 3 (this page)
print iprint(i)
print c, "\t", to stay on the same lineprint(c, end="\t")
details.iteritems()details.items()
range() builds the whole list in memoryrange() produces numbers one at a time
"%d : %s" % (digit, word)f"{digit} : {word}"

The original Pythofrank pages

Pythofrank was the first version of this site. The 2017 pages are still online exactly as they were written, with their original Python 2.7 code.

Next in the basics path: Python Functions.