Repeating the execution of a block of code is called iteration. Python can do this with two loop options:
- While loop
- For loop
The while loop executes code as long as a condition is true. When the condition equals false, we exit the loop. We check the condition each time we do another iteration. A while loop is useful when you don’t know beforehand how many loop iterations you need. In this lesson, I’ll show you how to use the while loop in Python.
Here is a basic example:
The while loop will run as long as the variable “counter” is below 3. We print a message, then increase the value of our variable by 1. Once the counter equals 3, the loop condition equals false and we exit the loop.
With the break statement, we can exit the while loop even though the while condition equals true. Here’s an example:
When the value of the variable “counter” equals 2, we break out of the while loop.
The continue statement stops the current iteration and continues with the next one. Here is our code:
Our code skips value 2, because of the continue statement. The loop continue until the while condition equals false.
The else statement runs some code when the condition of the while loop no longer equals true. Here’s how to do it:
You learned how to use the Python while loop:
- The while loop keeps iterating until the condition we set equals false.
- The break statement stops the loop even though the while condition still equals true.
- The continue statement skips the current iteration and continues with the next one.
- The else statement runs code when the loop finishes and the while condition is false.
I hope you enjoyed this lesson. If you have any questions, please leave a comment.