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:

Unlock This Lesson for Free - No Payment Required!

If you like to keep on reading, register now!

  • Learn CCNA, CCNP and CCIE R&S. Explained As Simple As Possible.
  • Get Instant Access to this Full Lesson, Completely for Free!
  • Unlock More to Read. More Lessons Added Every Week!
  • Content created by Rene Molenaar (CCIE #41726)
1997 Sign Ups in the last 30 days

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