Python How to Try Again After Try and Except
Watch At present This tutorial has a related video grade created by the Real Python team. Lookout it together with the written tutorial to deepen your understanding: Mastering While Loops
Iteration means executing the same cake of code over and over, potentially many times. A programming construction that implements iteration is chosen a loop.
In programming, in that location 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 condition is met.
-
With definite iteration, the number of times the designated block will be executed is specified explicitly at the fourth dimension the loop starts.
In this tutorial, you lot'll:
- Larn well-nigh the
whileloop, the Python command structure used for indefinite iteration - See how to suspension out of a loop or loop iteration prematurely
- Explore space loops
When you're finished, you should have a good grasp of how to use indefinite iteration in Python.
The while Loop
Let's see how Python'southward 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 ( s ) > <statement(due south)> represents the cake to be repeatedly executed, frequently referred to as the body of the loop. This is denoted with indentation, just 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 body.
When a while loop is encountered, <expr> is first evaluated in Boolean context. If information technology is true, the loop body is executed. Then <expr> is checked again, and if still true, the torso is executed again. This continues until <expr> becomes simulated, at which betoken program execution proceeds to the first statement across the loop body.
Consider this loop:
>>>
1 >>> n = 5 2 >>> while n > 0 : 3 ... n -= ane four ... impress ( n ) 5 ... 6 4 7 3 8 2 9 1 ten 0 Here'southward what'due south happening in this example:
-
northwardis initially5. The expression in thewhileargument header on line two isn > 0, which is true, so the loop torso executes. Inside the loop body on line 3,nis decremented byaneto4, and then printed. -
When the body of the loop has finished, program execution returns to the meridian of the loop at line 2, and the expression is evaluated again. It is still true, and then the torso executes again, and
3is printed. -
This continues until
due northbecomes0. At that indicate, when the expression is tested, it is false, and the loop terminates. Execution would resume at the first argument following the loop body, but at that place isn't one in this case.
Note that the controlling expression of the while loop is tested starting time, before anything else happens. If it'south fake to start with, the loop body will never be executed at all:
>>>
>>> n = 0 >>> while northward > 0 : ... n -= one ... print ( n ) ... In the example to a higher place, when the loop is encountered, n is 0. The decision-making expression n > 0 is already faux, so the loop body never executes.
Here's some other while loop involving a list, rather than a numeric comparison:
>>>
>>> a = [ 'foo' , 'bar' , 'baz' ] >>> while a : ... print ( a . pop ( - ane )) ... 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 true as long as it has elements in information technology. Once all the items have been removed with the .popular() method and the list is empty, a is imitation, and the loop terminates.
The Python break and continue Statements
In each case you accept seen so far, the entire trunk of the while loop is executed on each iteration. Python provides ii keywords that cease a loop iteration prematurely:
-
The Python
breakstatement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body. -
The Python
go onstatement 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 again or terminate.
The distinction between break and go on is demonstrated in the following diagram:
Hither'due south a script file called intermission.py that demonstrates the break statement:
one north = 5 ii while n > 0 : 3 n -= 1 4 if n == 2 : 5 interruption six print ( northward ) seven print ( 'Loop ended.' ) Running break.py from a control-line interpreter produces the post-obit output:
C:\Users\john\Documents>python break.py four three Loop concluded. When due north becomes 2, the break statement is executed. The loop is terminated completely, and programme execution jumps to the impress() statement on line 7.
The side by side script, continue.py, is identical except for a continue statement in place of the break:
i n = five 2 while north > 0 : iii north -= one 4 if north == 2 : five proceed half-dozen print ( northward ) 7 print ( 'Loop ended.' ) The output of continue.py looks similar this:
C:\Users\john\Documents>python keep.py 4 iii 1 0 Loop ended. This time, when n is 2, the go along statement causes termination of that iteration. Thus, two isn't printed. Execution returns to the acme of the loop, the condition is re-evaluated, and information technology is nonetheless true. The loop resumes, terminating when n becomes 0, every bit previously.
The else Clause
Python allows an optional else clause at the terminate of a while loop. This is a unique feature of Python, non found in nigh other programming languages. The syntax is shown below:
while < expr > : < argument ( s ) > else : < additional_statement ( s ) > The <additional_statement(s)> specified in the else clause will be executed when the while loop terminates.
Nigh at present, you lot may be thinking, "How is that useful?" You could accomplish the same thing past putting those statements immediately after the while loop, without the else:
while < expr > : < statement ( s ) > < additional_statement ( due south ) > What'south the difference?
In the latter instance, without the else clause, <additional_statement(s)> will exist executed after the while loop terminates, no affair what.
When <additional_statement(s)> are placed in an else clause, they will be executed only if the loop terminates "past exhaustion"—that is, if the loop iterates until the controlling condition becomes simulated. If the loop is exited by a interruption statement, the else clause won't exist executed.
Consider the post-obit example:
>>>
>>> north = 5 >>> while n > 0 : ... north -= ane ... print ( n ) ... else : ... print ( 'Loop done.' ) ... 4 3 2 1 0 Loop done. In this case, the loop repeated until the status was exhausted: northward became 0, so n > 0 became faux. Because the loop lived out its natural life, so to speak, the else clause was executed. Now observe the difference here:
>>>
>>> n = 5 >>> while n > 0 : ... n -= 1 ... print ( n ) ... if n == 2 : ... break ... else : ... print ( 'Loop done.' ) ... 4 three 2 This loop is terminated prematurely with intermission, and then the else clause isn't executed.
It may seem as if the meaning of the give-and-take else doesn't quite fit the while loop also equally it does the if statement. Guido van Rossum, the creator of Python, has actually said that, if he had information technology to practise again, he'd leave the while loop'due south else clause out of the linguistic communication.
Ane of the following interpretations might help to make it more intuitive:
-
Think of the header of the loop (
while north > 0) as anifargument (if n > 0) that gets executed over and over, with theelseclause finally being executed when the condition becomes false. -
Call up of
elseequally though it werenobreak, in that the block that follows gets executed if in that location wasn't abreak.
If yous 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? Ane common situation is if you are searching a list for a specific item. You tin use break to get out the loop if the detail is found, and the else clause can contain code that is meant to be executed if the item isn't found:
>>>
>>> a = [ 'foo' , 'bar' , 'baz' , 'qux' ] >>> s = 'corge' >>> i = 0 >>> while i < len ( a ): ... if a [ i ] == s : ... # Processing for item found ... suspension ... i += 1 ... else : ... # Processing for item non constitute ... print ( due south , 'not found in list.' ) ... corge not found in listing. An else clause with a while loop is a fleck of an oddity, not often seen. But don't shy away from information technology if y'all notice a state of affairs in which you feel it adds clarity to your code!
Space Loops
Suppose you write a while loop that theoretically never ends. Sounds weird, right?
Consider this instance:
>>>
>>> while Truthful : ... print ( 'foo' ) ... foo foo foo . . . foo foo foo KeyboardInterrupt Traceback (most recent call last): File "<pyshell#2>", line two, in <module> print ( 'foo' ) This lawmaking was terminated by Ctrl + C , which generates an interrupt from the keyboard. Otherwise, it would have gone on unendingly. Many foo output lines have been removed and replaced past the vertical ellipsis in the output shown.
Conspicuously, Truthful volition never be false, or we're all in very large problem. Thus, while Truthful: initiates an infinite loop that will theoretically run forever.
Maybe that doesn't audio similar something you'd want to do, but this pattern is actually quite common. For example, you might write code for a service that starts upwards and runs forever accepting service requests. "Forever" in this context ways until you close it down, or until the heat expiry of the universe, whichever comes first.
More prosaically, remember that loops can be cleaved out of with the interruption statement. It may be more straightforward to cease a loop based on weather condition recognized within the loop body, rather than on a condition evaluated at the top.
Here's another variant of the loop shown to a higher place that successively removes items from a list using .popular() until information technology is empty:
>>>
>>> a = [ 'foo' , 'bar' , 'baz' ] >>> while True : ... if not a : ... break ... impress ( a . popular ( - one )) ... baz bar foo When a becomes empty, not a becomes true, and the intermission argument exits the loop.
Y'all tin can too specify multiple pause statements in a loop:
while True : if < expr1 > : # Ane condition for loop termination interruption ... if < expr2 > : # Another termination status suspension ... if < expr3 > : # Notwithstanding another break In cases similar this, where there are multiple reasons to end the loop, it is often cleaner to break out from several unlike locations, rather than try to specify all the termination conditions in the loop header.
Infinite loops can be very useful. Just remember that you must ensure the loop gets cleaved out of at some point, so it doesn't truly get space.
Nested while Loops
In general, Python control structures tin can be nested within i some other. For example, if/elif/else conditional statements can be nested:
if age < 18 : if gender == 'M' : print ( 'son' ) else : print ( 'girl' ) elif age >= 18 and historic period < 65 : if gender == 'M' : print ( 'father' ) else : impress ( 'mother' ) else : if gender == 'Grand' : print ( 'grandfather' ) else : print ( 'grandmother' ) Similarly, a while loop can be contained inside 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 suspension or keep statement plant within nested loops applies to the nearest enclosing loop:
while < expr1 > : statement statement while < expr2 > : statement statement break # Applies to while <expr2>: loop break # Applies to while <expr1>: loop Additionally, while loops can be nested inside if/elif/else statements, and vice versa:
if < expr > : statement while < expr > : argument argument else : while < expr > : statement statement statement while < expr > : if < expr > : statement elif < expr > : statement else : statement if < expr > : statement In fact, all the Python control structures can exist intermingled with one another to whatever extent you need. That is as it should be. Imagine how frustrating it would exist if there were unexpected restrictions like "A while loop tin can't exist contained inside an if statement" or "while loops tin but be nested within one another at almost 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.
1-Line while Loops
As with an if statement, a while loop tin be specified on i line. If there are multiple statements in the block that makes upward the loop trunk, they tin be separated by semicolons (;):
>>>
>>> northward = 5 >>> while n > 0 : n -= i ; impress ( n ) 4 3 two one 0 This only works with simple statements though. You can't combine ii chemical compound statements into one line. Thus, you tin can specify a while loop all on one line as above, and you write an if statement on one line:
>>>
>>> if True : print ( 'foo' ) foo But you can't do this:
>>>
>>> while northward > 0 : northward -= i ; if True : impress ( 'foo' ) SyntaxError: invalid syntax Remember that PEP 8 discourages multiple statements on ane line. And so you probably shouldn't be doing whatever of this very ofttimes anyhow.
Determination
In this tutorial, yous learned about indefinite iteration using the Python while loop. Y'all're at present able to:
- Construct basic and circuitous
whileloops - Interrupt loop execution with
breakandcontinue - Use the
elseclause with awhileloop - Bargain with infinite loops
You lot should now have a proficient 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.
Sentry Now This tutorial has a related video course created past the Real Python team. Watch information technology together with the written tutorial to deepen your agreement: Mastering While Loops
Source: https://realpython.com/python-while-loop/
0 Response to "Python How to Try Again After Try and Except"
Post a Comment