Watch At present This tutorial has a related video course created by the Real Python squad. Watch information technology together with the written tutorial to deepen your understanding: Mastering While Loops

Iteration means executing the same block of code over and over, potentially many times. A programming structure that implements iteration is called a loop.

In programming, at that place are two types of iteration, indefinite and definite:

  • With indefinite iteration, the number of times the loop is executed isn't specified explicitly in advance. Rather, the designated block is executed repeatedly as long as some status is met.

  • With definite iteration, the number of times the designated block volition be executed is specified explicitly at the time the loop starts.

In this tutorial, you'll:

  • Learn nigh the while loop, the Python control structure used for indefinite iteration
  • Encounter how to break out of a loop or loop iteration prematurely
  • Explore space loops

When you're finished, you should accept a good grasp of how to use indefinite iteration in Python.

The while Loop

Allow's see how Python's while statement is used to construct loops. We'll offset unproblematic and embellish every bit we become.

The format of a rudimentary while loop is shown below:

                                            while                <                expr                >                :                <                argument                (                s                )                >                          

<argument(south)> represents the block to be repeatedly executed, often referred to every bit the body of the loop. This is denoted with indentation, merely as in an if statement.

The controlling expression, <expr>, typically involves one or more variables that are initialized prior to starting the loop and then modified somewhere in the loop trunk.

When a while loop is encountered, <expr> is first evaluated in Boolean context. If information technology is true, the loop body is executed. So <expr> is checked again, and if nonetheless truthful, the torso is executed again. This continues until <expr> becomes faux, at which point program execution proceeds to the first statement beyond the loop torso.

Consider this loop:

>>>

                                                              1                >>>                                northward                =                5                                  2                >>>                                while                n                >                0                :                                  3                ...                                n                -=                1                                  four                ...                                print                (                north                )                                  five                ...                                  6                4                                  7                iii                                  8                2                                  9                1                10                0                          

Here's what'southward happening in this example:

  • n is initially 5. The expression in the while statement header on line 2 is n > 0, which is true, and then the loop body executes. Inside the loop body on line 3, north is decremented by 1 to 4, and then printed.

  • When the body of the loop has finished, program execution returns to the top of the loop at line 2, and the expression is evaluated again. It is still true, and so the body executes again, and iii is printed.

  • This continues until n becomes 0. At that point, when the expression is tested, information technology is false, and the loop terminates. Execution would resume at the outset statement following the loop body, but there isn't one in this case.

Note that the controlling expression of the while loop is tested offset, earlier anything else happens. If it's false to start with, the loop body will never be executed at all:

>>>

                                            >>>                                n                =                0                >>>                                while                n                >                0                :                ...                                n                -=                one                ...                                print                (                n                )                ...                          

In the case above, when the loop is encountered, n is 0. The controlling expression n > 0 is already false, so the loop body never executes.

Here's another while loop involving a list, rather than a numeric comparing:

>>>

                                            >>>                                a                =                [                'foo'                ,                'bar'                ,                'baz'                ]                >>>                                while                a                :                ...                                impress                (                a                .                pop                (                -                1                ))                ...                baz                bar                foo                          

When a list is evaluated in Boolean context, it is truthy if it has elements in it and falsy if it is empty. In this case, a is truthful as long equally it has elements in information technology. Once all the items have been removed with the .pop() method and the list is empty, a is false, and the loop terminates.

The Python break and keep Statements

In each instance you lot take seen so far, the entire body of the while loop is executed on each iteration. Python provides two keywords that terminate a loop iteration prematurely:

  • The Python suspension statement immediately terminates a loop entirely. Program execution proceeds to the start statement post-obit the loop body.

  • The Python continue statement immediately terminates the current loop iteration. Execution jumps to the top of the loop, and the controlling expression is re-evaluated to determine whether the loop volition execute over again or terminate.

The distinction between intermission and continue is demonstrated in the following diagram:

Python while loops: break and continue statements
break and proceed

Hither'south a script file called break.py that demonstrates the intermission statement:

                                                              i                due north                =                5                                  2                while                n                >                0                :                                  three                n                -=                one                                  4                if                n                ==                ii                :                                  five                                  break                                                  half dozen                impress                (                n                )                                  vii                impress                (                'Loop concluded.'                )                          

Running intermission.py from a command-line interpreter produces the following output:

                                            C:\Users\john\Documents>python pause.py                4                3                Loop concluded.                          

When north becomes 2, the break statement is executed. The loop is terminated completely, and plan execution jumps to the print() statement on line 7.

The next script, continue.py, is identical except for a go on argument in identify of the break:

                                                              1                north                =                5                                  2                while                north                >                0                :                                  3                n                -=                1                                  4                if                due north                ==                2                :                                  five                                  go on                                                  half dozen                print                (                n                )                                  vii                print                (                'Loop ended.'                )                          

The output of keep.py looks like this:

                                            C:\Users\john\Documents>python go along.py                4                iii                1                0                Loop ended.                          

This time, when due north is 2, the continue statement causes termination of that iteration. Thus, 2 isn't printed. Execution returns to the top of the loop, the condition is re-evaluated, and it is still true. The loop resumes, terminating when north becomes 0, as previously.

The else Clause

Python allows an optional else clause at the end of a while loop. This is a unique feature of Python, not plant in most other programming languages. The syntax is shown beneath:

                                            while                <                expr                >                :                <                statement                (                southward                )                >                else                :                <                additional_statement                (                south                )                >                          

The <additional_statement(s)> specified in the else clause will exist executed when the while loop terminates.

thought balloon

About now, yous may be thinking, "How is that useful?" You could accomplish the same affair past putting those statements immediately after the while loop, without the else:

                                            while                <                expr                >                :                <                statement                (                southward                )                >                <                additional_statement                (                southward                )                >                          

What's the divergence?

In the latter case, without the else clause, <additional_statement(s)> will be executed afterward the while loop terminates, no matter what.

When <additional_statement(s)> are placed in an else clause, they will be executed just if the loop terminates "by burnout"—that is, if the loop iterates until the controlling condition becomes imitation. If the loop is exited past a break argument, the else clause won't be executed.

Consider the post-obit instance:

>>>

                                            >>>                                n                =                5                >>>                                while                northward                >                0                :                ...                                due north                -=                i                ...                                print                (                n                )                                  ...                                    else                  :                                                  ...                                    impress                  (                  'Loop washed.'                  )                                ...                4                three                2                i                0                Loop washed.                          

In this case, the loop repeated until the condition was wearied: n became 0, so n > 0 became false. Because the loop lived out its natural life, so to speak, the else clause was executed. At present observe the difference here:

>>>

                                            >>>                                n                =                5                >>>                                while                n                >                0                :                ...                                n                -=                one                ...                                print                (                n                )                                  ...                                    if                  n                  ==                  ii                  :                                                  ...                                    break                                ...                                else                :                ...                                impress                (                'Loop done.'                )                ...                iv                3                2                          

This loop is terminated prematurely with intermission, and so the else clause isn't executed.

It may seem as if the significant of the give-and-take else doesn't quite fit the while loop as well as information technology does the if statement. Guido van Rossum, the creator of Python, has actually said that, if he had it to do over over again, he'd leave the while loop's else clause out of the language.

Ane of the following interpretations might help to brand information technology more than intuitive:

  • Think of the header of the loop (while n > 0) as an if statement (if northward > 0) that gets executed over and over, with the else clause finally being executed when the status becomes false.

  • Call up of else equally though it were nobreak, in that the block that follows gets executed if in that location wasn't a break.

If you don't find either of these interpretations helpful, then feel free to ignore them.

When might an else clause on a while loop be useful? One mutual situation is if yous are searching a list for a specific detail. You can use break to exit the loop if the item is found, and the else clause can incorporate code that is meant to be executed if the item isn't institute:

>>>

                                            >>>                                a                =                [                'foo'                ,                'bar'                ,                'baz'                ,                'qux'                ]                >>>                                s                =                'corge'                >>>                                i                =                0                >>>                                while                i                <                len                (                a                ):                ...                                if                a                [                i                ]                ==                s                :                ...                                # Processing for item plant                ...                                break                ...                                i                +=                i                ...                                else                :                ...                                # Processing for particular not found                ...                                print                (                s                ,                'not constitute in list.'                )                ...                corge not institute in list.                          

An else clause with a while loop is a bit of an oddity, non often seen. But don't shy away from it if you find a situation in which yous feel information technology adds clarity to your lawmaking!

Infinite Loops

Suppose you write a while loop that theoretically never ends. Sounds weird, correct?

Consider this instance:

>>>

                                            >>>                                while                True                :                ...                                print                (                'foo'                )                ...                foo                foo                foo                                  .                                  .                                  .                foo                foo                foo                KeyboardInterrupt                Traceback (most recent telephone call terminal):                File                "<pyshell#ii>", line                two, in                <module>                impress                (                'foo'                )                          

This code was terminated past Ctrl + C , which generates an interrupt from the keyboard. Otherwise, information technology would have gone on unendingly. Many foo output lines have been removed and replaced by the vertical ellipsis in the output shown.

Conspicuously, True volition never be faux, or we're all in very big problem. Thus, while True: initiates an infinite loop that will theoretically run forever.

Perchance that doesn't audio like something you'd want to do, but this pattern is really quite common. For instance, yous might write code for a service that starts up and runs forever accepting service requests. "Forever" in this context ways until you close it downwardly, or until the estrus death of the universe, whichever comes first.

More prosaically, remember that loops can be cleaved out of with the break statement. It may be more straightforward to terminate a loop based on atmospheric condition recognized within the loop body, rather than on a condition evaluated at the top.

Here's another variant of the loop shown above that successively removes items from a list using .popular() until it is empty:

>>>

                                            >>>                                a                =                [                'foo'                ,                'bar'                ,                'baz'                ]                >>>                                while                True                :                ...                                if                not                a                :                ...                                break                ...                                print                (                a                .                pop                (                -                1                ))                ...                baz                bar                foo                          

When a becomes empty, not a becomes true, and the pause statement exits the loop.

Y'all can too specify multiple interruption statements in a loop:

                                            while                True                :                if                <                expr1                >                :                # I condition for loop termination                pause                ...                if                <                expr2                >                :                # Another termination condition                break                ...                if                <                expr3                >                :                # Nevertheless another                break                          

In cases like this, where there are multiple reasons to end the loop, information technology is often cleaner to suspension out from several dissimilar locations, rather than try to specify all the termination weather condition in the loop header.

Infinite loops can exist very useful. Just remember that you lot must ensure the loop gets cleaved out of at some point, so information technology doesn't truly go infinite.

Nested while Loops

In full general, Python command structures can be nested within i another. For example, if/elif/else conditional statements can be nested:

                                            if                historic period                <                18                :                if                gender                ==                'M'                :                print                (                'son'                )                else                :                print                (                'daughter'                )                elif                age                >=                18                and                historic period                <                65                :                if                gender                ==                'M'                :                print                (                'father'                )                else                :                print                (                'mother'                )                else                :                if                gender                ==                'One thousand'                :                print                (                'gramps'                )                else                :                print                (                'grandmother'                )                          

Similarly, a while loop can be contained within another while loop, as shown here:

>>>

                                            >>>                                a                =                [                'foo'                ,                'bar'                ]                                  >>>                                    while                  len                  (                  a                  ):                                ...                                impress                (                a                .                pop                (                0                ))                ...                                b                =                [                'baz'                ,                'qux'                ]                                  ...                                    while                  len                  (                  b                  ):                                ...                                print                (                '>'                ,                b                .                pop                (                0                ))                ...                foo                > baz                > qux                bar                > baz                > qux                          

A break or continue statement constitute inside nested loops applies to the nearest enclosing loop:

                                            while                <                expr1                >                :                statement                statement                while                <                expr2                >                :                statement                statement                                  suspension                  # Applies to while <expr2>: loop                                                  interruption                  # Applies to while <expr1>: loop                                          

Additionally, while loops can be nested inside if/elif/else statements, and vice versa:

                                            if                <                expr                >                :                argument                while                <                expr                >                :                statement                statement                else                :                while                <                expr                >                :                statement                statement                statement                          
                                            while                <                expr                >                :                if                <                expr                >                :                statement                elif                <                expr                >                :                statement                else                :                argument                if                <                expr                >                :                statement                          

In fact, all the Python control structures tin can exist intermingled with 1 some other to whatever extent you demand. That is as it should be. Imagine how frustrating it would be if there were unexpected restrictions like "A while loop can't be independent inside an if statement" or "while loops can only be nested inside 1 some other at most four deep." You'd have a very hard time remembering them all.

Seemingly capricious numeric or logical limitations are considered a sign of poor plan linguistic communication design. Happily, you lot won't find many in Python.

One-Line while Loops

Every bit with an if argument, a while loop tin be specified on one line. If there are multiple statements in the block that makes upwards the loop body, they can be separated by semicolons (;):

>>>

                                            >>>                                north                =                5                >>>                                while                n                >                0                :                n                -=                1                ;                print                (                n                )                4                three                2                1                0                          

This only works with simple statements though. You lot tin can't combine two chemical compound statements into i line. Thus, y'all tin specify a while loop all on one line every bit above, and yous write an if argument on one line:

>>>

                                            >>>                                if                True                :                print                (                'foo'                )                foo                          

But you can't exercise this:

>>>

                                            >>>                                while                n                >                0                :                north                -=                1                ;                if                True                :                print                (                'foo'                )                SyntaxError: invalid syntax                          

Recollect that PEP 8 discourages multiple statements on one line. So you probably shouldn't be doing any of this very often anyhow.

Conclusion

In this tutorial, you learned virtually indefinite iteration using the Python while loop. You're now able to:

  • Construct bones and complex while loops
  • Interrupt loop execution with pause and continue
  • Use the else clause with a while loop
  • Deal with infinite loops

You should now have a skilful grasp of how to execute a piece of code repetitively.

The next tutorial in this series covers definite iteration with for loops—recurrent execution where the number of repetitions is specified explicitly.

Watch Now This tutorial has a related video course created by the Real Python team. Scout it together with the written tutorial to deepen your agreement: Mastering While Loops