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.

example 1 · press Run, then edit and run again

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.

example 2 · press Run, then edit and run again

Asking until the answer is valid

example 3 · press Run, then edit and run again

💡 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:

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.

More Python concepts