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.
range() in detail
range(5)gives 0, 1, 2, 3, 4 (it stops before 5).range(1, 11)gives 1 to 10.range(5, 0, -1)counts down 5, 4, 3, 2, 1, great for countdowns and for dropping counters to the bottom row.
enumerate() and zip()
enumerate() gives you a position and an item together. zip() walks through two lists side by side.
💡 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:
- #01☆☆☆
Tic Tac Toe in Python
Learn Lists, Functions and if, elif and else.
- #09☆☆☆
Connect Four-Style Game in Python
Learn 2D lists and grids, Lists and Functions.
- #10☆☆☆
Minesweeper-Style Game in Python
Learn 2D lists and grids, Functions and for loops.
- #11☆☆☆
Sudoku in Python
Learn 2D lists and grids, Functions and for loops.
- #16☆☆☆
Coin Flip in Python
Learn The random module, for loops and Variables.
- #17☆☆☆
Turtle Race in Python
Learn Turtle graphics, Lists and for loops.
- #18☆☆☆
Python Quiz Game
Learn Dictionaries, Lists and for loops.
- #19☆☆☆
Math Quiz Game in Python
Learn The random module, Dictionaries and for loops.
- #20☆☆☆
Typing Speed Game in Python
Learn Strings, Functions and for loops.
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.