Python Make It So You Dont Have to Type the Same Code Over and Over Again
Watch Now This tutorial has a related video grade created past the Real Python team. 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 construction that implements iteration is called a loop.
In programming, there are 2 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 cake is executed repeatedly as long as some condition is met.
-
With definite iteration, the number of times the designated cake will be executed is specified explicitly at the time the loop starts.
In this tutorial, you lot'll:
- Learn about the
while
loop, the Python command structure used for indefinite iteration - Meet how to break out of a loop or loop iteration prematurely
- Explore space loops
When you're finished, y'all should take a good grasp of how to use indefinite iteration in Python.
The while
Loop
Permit's see how Python's while
statement is used to construct loops. We'll start unproblematic and embellish as we go.
The format of a rudimentary while
loop is shown below:
while < expr > : < statement ( due south ) >
<statement(south)>
represents the block to exist repeatedly executed, frequently referred to as the body of the loop. This is denoted with indentation, just equally 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 body.
When a while
loop is encountered, <expr>
is showtime evaluated in Boolean context. If it is true, the loop torso is executed. Then <expr>
is checked over again, and if still true, the body is executed over again. This continues until <expr>
becomes false, at which point program execution gain to the start statement across the loop body.
Consider this loop:
>>>
1 >>> northward = 5 2 >>> while n > 0 : 3 ... north -= 1 four ... print ( n ) 5 ... 6 iv vii 3 8 ii 9 one 10 0
Here'due south what'southward happening in this example:
-
n
is initially5
. The expression in thewhile
argument header on line two isn > 0
, which is true, and so the loop body executes. Inside the loop trunk on line iii,n
is decremented byone
to4
, and and then printed. -
When the body of the loop has finished, program execution returns to the pinnacle of the loop at line 2, and the expression is evaluated again. It is notwithstanding truthful, and so the trunk executes again, and
iii
is printed. -
This continues until
n
becomes0
. At that point, when the expression is tested, it is false, and the loop terminates. Execution would resume at the first statement following the loop body, merely there isn't one in this case.
Annotation that the controlling expression of the while
loop is tested first, before anything else happens. If it'southward imitation to outset with, the loop body will never be executed at all:
>>>
>>> n = 0 >>> while n > 0 : ... n -= i ... print ( n ) ...
In the example to a higher place, when the loop is encountered, northward
is 0
. The decision-making expression north > 0
is already false, so the loop torso never executes.
Here's another while
loop involving a list, rather than a numeric comparison:
>>>
>>> a = [ 'foo' , 'bar' , 'baz' ] >>> while a : ... print ( 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 example, a
is true every bit long as information technology has elements in it. Once all the items have been removed with the .pop()
method and the listing is empty, a
is false, and the loop terminates.
The Python pause
and continue
Statements
In each case you lot have seen so far, the entire body of the while
loop is executed on each iteration. Python provides 2 keywords that terminate a loop iteration prematurely:
-
The Python
break
statement immediately terminates a loop entirely. Program execution proceeds to the first statement following 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 make up one's mind whether the loop will execute again or terminate.
The distinction between intermission
and continue
is demonstrated in the following diagram:
Here'due south a script file chosen break.py
that demonstrates the interruption
statement:
1 n = five ii while n > 0 : iii northward -= i 4 if n == ii : v intermission 6 print ( n ) 7 print ( 'Loop ended.' )
Running break.py
from a control-line interpreter produces the following output:
C:\Users\john\Documents>python break.py 4 3 Loop concluded.
When n
becomes 2
, the break
argument 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 continue
statement in place of the break
:
i north = five two while due north > 0 : 3 n -= ane 4 if due north == 2 : 5 continue 6 print ( north ) 7 impress ( 'Loop concluded.' )
The output of keep.py
looks like this:
C:\Users\john\Documents>python continue.py 4 3 1 0 Loop concluded.
This fourth dimension, when n
is 2
, the continue
statement causes termination of that iteration. Thus, ii
isn't printed. Execution returns to the tiptop of the loop, the condition is re-evaluated, and information technology is notwithstanding true. The loop resumes, terminating when north
becomes 0
, every bit 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 establish in most other programming languages. The syntax is shown below:
while < expr > : < statement ( s ) > else : < additional_statement ( s ) >
The <additional_statement(s)>
specified in the else
clause will be executed when the while
loop terminates.
About now, you may be thinking, "How is that useful?" You could accomplish the same matter past putting those statements immediately after the while
loop, without the else
:
while < expr > : < statement ( south ) > < additional_statement ( s ) >
What's the divergence?
In the latter case, without the else
clause, <additional_statement(s)>
volition be executed after the while
loop terminates, no matter what.
When <additional_statement(due south)>
are placed in an else
clause, they volition be executed only if the loop terminates "by exhaustion"—that is, if the loop iterates until the controlling status becomes false. If the loop is exited past a intermission
statement, the else
clause won't be executed.
Consider the following example:
>>>
>>> n = 5 >>> while n > 0 : ... north -= 1 ... print ( n ) ... else : ... print ( 'Loop done.' ) ... 4 3 ii 1 0 Loop done.
In this instance, the loop repeated until the condition was exhausted: north
became 0
, so northward > 0
became simulated. Because the loop lived out its natural life, so to speak, the else
clause was executed. Now observe the difference here:
>>>
>>> due north = 5 >>> while n > 0 : ... n -= 1 ... print ( n ) ... if n == 2 : ... intermission ... else : ... print ( 'Loop done.' ) ... 4 3 two
This loop is terminated prematurely with interruption
, so the else
clause isn't executed.
It may seem as if the meaning of the word else
doesn't quite fit the while
loop also as it does the if
statement. Guido van Rossum, the creator of Python, has actually said that, if he had it to practise over once again, he'd leave the while
loop'due south else
clause out of the language.
One of the following interpretations might help to make it more intuitive:
-
Think of the header of the loop (
while due north > 0
) equally anif
statement (if north > 0
) that gets executed over and over, with theelse
clause finally being executed when the condition becomes imitation. -
Recall of
else
every bit though it werenobreak
, in that the cake that follows gets executed if there wasn't abreak
.
If you don't find either of these interpretations helpful, and then experience free to ignore them.
When might an else
clause on a while
loop exist useful? One common situation is if you lot are searching a list for a specific item. You tin can apply interruption
to exit the loop if the item is establish, and the else
clause can incorporate lawmaking that is meant to exist executed if the item isn't constitute:
>>>
>>> a = [ 'foo' , 'bar' , 'baz' , 'qux' ] >>> south = 'corge' >>> i = 0 >>> while i < len ( a ): ... if a [ i ] == s : ... # Processing for item found ... suspension ... i += one ... else : ... # Processing for detail not found ... print ( s , 'not found in list.' ) ... corge not institute in list.
An else
clause with a while
loop is a bit of an oddity, not oft seen. Only don't shy away from it if you find a state of affairs in which you feel it adds clarity to your lawmaking!
Space Loops
Suppose you write a while
loop that theoretically never ends. Sounds weird, right?
Consider this example:
>>>
>>> while Truthful : ... impress ( 'foo' ) ... foo foo foo . . . foo foo foo KeyboardInterrupt Traceback (most contempo telephone call last): File "<pyshell#ii>", line 2, in <module> print ( 'foo' )
This code was terminated by 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 past the vertical ellipsis in the output shown.
Clearly, True
will never be simulated, or we're all in very big trouble. Thus, while Truthful:
initiates an space loop that will theoretically run forever.
Maybe that doesn't audio like something you'd want to do, only this design is actually quite common. For example, yous might write lawmaking for a service that starts upward and runs forever accepting service requests. "Forever" in this context ways until you shut it down, or until the estrus decease of the universe, whichever comes kickoff.
More than prosaically, retrieve that loops can be broken out of with the pause
statement. Information technology may be more straightforward to finish a loop based on conditions recognized within the loop torso, rather than on a condition evaluated at the tiptop.
Here's another variant of the loop shown to a higher place that successively removes items from a list using .pop()
until it is empty:
>>>
>>> a = [ 'foo' , 'bar' , 'baz' ] >>> while True : ... if not a : ... break ... impress ( a . pop ( - 1 )) ... baz bar foo
When a
becomes empty, not a
becomes truthful, and the break
statement exits the loop.
Yous can also specify multiple pause
statements in a loop:
while True : if < expr1 > : # One status for loop termination break ... if < expr2 > : # Another termination status break ... if < expr3 > : # Yet another break
In cases like this, where at that place are multiple reasons to end the loop, it is often cleaner to suspension
out from several different locations, rather than endeavor to specify all the termination conditions in the loop header.
Space loops can exist very useful. Just remember that you lot must ensure the loop gets broken out of at some betoken, so it doesn't truly get infinite.
Nested while
Loops
In general, Python control structures can be nested within one another. For example, if
/elif
/else
conditional statements tin be nested:
if historic period < 18 : if gender == 'Grand' : print ( 'son' ) else : print ( 'daughter' ) elif age >= 18 and age < 65 : if gender == 'Yard' : print ( 'begetter' ) else : print ( 'mother' ) else : if gender == 'M' : print ( 'grandfather' ) else : print ( 'grandmother' )
Similarly, a while
loop can be contained inside another while
loop, equally shown hither:
>>>
>>> a = [ 'foo' , 'bar' ] >>> while len ( a ): ... impress ( a . popular ( 0 )) ... b = [ 'baz' , 'qux' ] ... while len ( b ): ... print ( '>' , b . pop ( 0 )) ... foo > baz > qux bar > baz > qux
A break
or go along
statement found within nested loops applies to the nearest enclosing loop:
while < expr1 > : argument statement while < expr2 > : argument statement interruption # Applies to while <expr2>: loop suspension # Applies to while <expr1>: loop
Additionally, while
loops tin 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 : statement if < expr > : statement
In fact, all the Python command structures can be intermingled with ane another to whatever extent you demand. That is as information technology should be. Imagine how frustrating it would exist if there were unexpected restrictions similar "A while
loop can't be contained within an if
statement" or "while
loops can only be nested within one another at most four deep." You'd have a very difficult time remembering them all.
Seemingly arbitrary numeric or logical limitations are considered a sign of poor program language design. Happily, you lot won't find many in Python.
One-Line while
Loops
As with an if
statement, a while
loop can exist specified on one line. If in that location are multiple statements in the cake that makes upwardly the loop body, they can exist separated by semicolons (;
):
>>>
>>> n = 5 >>> while due north > 0 : n -= one ; print ( n ) 4 three 2 1 0
This but works with simple statements though. Yous tin't combine two compound statements into one line. Thus, yous can specify a while
loop all on one line as above, and you lot write an if
statement on one line:
>>>
>>> if True : impress ( 'foo' ) foo
Only you tin't do this:
>>>
>>> while n > 0 : n -= 1 ; if Truthful : print ( 'foo' ) SyntaxError: invalid syntax
Remember that PEP eight discourages multiple statements on one line. And then you probably shouldn't be doing any of this very ofttimes anyhow.
Conclusion
In this tutorial, you learned about indefinite iteration using the Python while
loop. You're now able to:
- Construct basic and complex
while
loops - Interrupt loop execution with
break
andcontinue
- Use the
else
clause with awhile
loop - Deal with infinite loops
You should now have a practiced grasp of how to execute a piece of lawmaking 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 Existent Python team. Watch it together with the written tutorial to deepen your agreement: Mastering While Loops
Source: https://realpython.com/python-while-loop/
0 Response to "Python Make It So You Dont Have to Type the Same Code Over and Over Again"
Post a Comment