Python While Loop

Repeating the execution of a block of code is called iteration. Python can do this with two loop options:

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.


Forum Replies

  1. counter = 0
    
    while counter < 3:
        counter += 1
        if counter == 2:
            continue
            print("This is never executed")
        print("Counter value is %s" % counter)
    

    Should not it print “This is never executed” when counter values is 2 during the incrementing counter value loop?

  2. Hello Rupak

    The continue statement is used to stop the current iteration and continue with the next one. This means that:

    • when the counter is equal to 2, the continue statement is executed.
    • the loop stops there and goes back to the beginning without executing the next statements

    Therefore, the print("This is never executed") statement is never executed.

    I hope this has been helpful!

    Laz

Ask a question or join the discussion by visiting our Community Forum