Lesson Contents
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.
While Loop
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.
Break
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.
Continue Statement
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.
Else Statement
The else statement runs some code when the condition of the while loop no longer equals true. Here’s how to do it:
Conclusion
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.
Should not it print “This is never executed” when counter values is 2 during the incrementing counter value loop?
Hello Rupak
The
continue
statement is used to stop the current iteration and continue with the next one. This means that:continue
statement is executed.Therefore, the
print("This is never executed")
statement is never executed.I hope this has been helpful!
Laz