Python while Loops for Games
Python while loops explained with games: keep playing until someone wins, ask again on bad input, use break and continue, and avoid endless loops.
Almost every game has a main loop: "keep going while the game isn't over". A while loop repeats its indented block as long as its condition stays True.
while True with break
When you don't know how many turns it will take, loop forever and break out when the game ends. continue skips back to the top, which is perfect for ignoring bad input.
Asking until the answer is valid
💡 An endless loop happens when nothing inside the loop can make the condition False. On this site Stop always works, because the code runs in the background.
Games that use while loops
Practise this with 12 of the 20 games:
- #01☆☆☆
Tic Tac Toe in Python
Learn Lists, Functions and if, elif and else.
- #02☆☆☆
Rock Paper Scissors in Python
Learn The random module, Dictionaries and if, elif and else.
- #03☆☆☆
Snake Game in Python (Turtle)
Learn Turtle graphics, Lists and Functions.
- #04☆☆☆
Hangman in Python
Learn Strings, Lists and while loops.
- #05☆☆☆
Number Guessing Game in Python
Learn The random module, while loops and if, elif and else.
- #06☆☆☆
Pong-Style Paddle Game in Python
Learn Turtle graphics, Functions and if, elif and else.
- #08☆☆☆
Text Adventure Game in Python
Learn Dictionaries, Strings and while loops.
- #12☆☆☆
Battleship-Style Game in Python
Learn 2D lists and grids, The random module and Strings.
- #13☆☆☆
Maze Game in Python
Learn 2D lists and grids, Functions and Lists.
- #14☆☆☆
Higher or Lower Game in Python
Learn The random module, while loops and if, elif and else.
- #15☆☆☆
Word Guessing Game in Python
Learn Strings, Lists and Dictionaries.
- #17☆☆☆
Turtle Race in Python
Learn Turtle graphics, Lists and for loops.
Frequently asked questions
When should I use while instead of for?
Use while when you repeat until something happens (a win, a correct guess). Use for when you know how many times to repeat or are going through a list.
What does break do in Python?
break ends the nearest loop immediately and continues with the code after it.