Python for Loops for Games

Python for loops explained with games: count rounds with range(), go through lists, number items with enumerate() and pair things up with zip().

A for loop runs once for each item in a sequence. With range() it counts; with a list it visits every item. Games use it for rounds, players, rows of a grid and much more.

example 1 · press Run, then edit and run again

range() in detail

enumerate() and zip()

enumerate() gives you a position and an item together. zip() walks through two lists side by side.

example 2 · press Run, then edit and run again

💡 Off-by-one errors are the classic for-loop bug. If a loop runs one time too few, check the end number of range().

Games that use for loops

Practise this with 9 of the 20 games:

Frequently asked questions

How do I loop a specific number of times in Python?

for i in range(n): repeats n times, with i going from 0 to n - 1.

Can I change a list while looping over it?

It's risky: removing items while looping skips some. Loop over a copy (for x in items[:]) or build a new list instead.

More Python concepts