Ad space (banner)
🐍Python Lessons
Lesson 8 / 69

Loops (while statements)

This lesson covers looping with Python's while statement, so you can understand how it differs from for loops and choose the right one. It's written for anyone searching "Python while loop tutorial" or "Python infinite loop".

A while statement repeats "for as long as a condition holds true." Forget to update the relevant variable inside the loop, and you'll end up with an infinite loop. The general rule of thumb: use a for loop when you know in advance how many times to repeat, and a while loop when you don't know ahead of time when it will end.

The sample code loops as long as count is less than 5, incrementing it by 1 each time with count += 1. The condition is checked at the top of the loop each time through; the moment it becomes False, the loop exits and execution continues on the next line.

A common trap is forgetting to update the variable the condition depends on, resulting in an infinite loop. If your browser or program seems to freeze, check the condition and the update step first. If you deliberately write something like while True:, you must include a break somewhere inside to exit the loop.

This control structure shines in situations where the number of repetitions isn't known ahead of time — programs that keep accepting user input, or searches that continue until a condition is met. The while-loop mindset also appears constantly in real code, such as a game's main loop.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)