A program’s
control flow is the orderin which the program’s code executes. The controlflow of a Python program is regulated by conditional statements,loops, and function calls. This section covers theif statement and for andwhile loops; functions are covered later in thischapter. Raising and handling exceptions also affects control flow;exceptions are covered in Chapter 6.
Flow of Execution Summary¶. When you are working with functions it is really important to know the order in which statements are executed. This is called the flow of execution or control flow and we’ve already talked about it a number of times so far. Flow of Execution: v The order in which statements are executed is called the flow of execution. V Execution always begins at the first statement of the program. V Statements are executed one at a time, in order, from top to bottom. code# Threading example import time, thread def myfunction(string, sleeptime, lock,.args): while True: lock.acquire time.sleep(sleeptime) lock.release time. A program’s control flow is the order in which the program’s code executes. The control flow of a Python program is regulated by conditional statements, loops, and function calls. This section covers the if statement and for and while loops; functions are covered later in this chapter.
Often, you need to execute somestatements only if some condition holds, or choose statements toexecute depending on several mutually exclusive conditions. ThePython compound statement
if , which usesif , elif , andelse clauses, lets you conditionally executeblocks of statements. Here’s the syntax for theif statement:
The
elif and else clauses areoptional. Note that unlike some languages, Python does not have aswitch statement, so you must useif , elif , andelse for all conditional processing.
Here’s a typical
if statement:
When there aremultiple statements in a clause (i.e., the clause controls a block ofstatements), the statements are placed on separate logical linesafter the line containing the clause’s keyword(known as the headerlineof the clause) and indented rightward from the header line. The blockterminates when the indentation returns to that of the clause header(or further left from there). When there is just a single simplestatement, as here, it can follow the : on thesame logical line as the header, but it can also be placed on aseparate logical line, immediately after the header line and indentedrightward from it. Many Python practitioners consider theseparate-line style more readable:
You can use any Python expression asthe condition in an
if or elif clause. When you use an expression this way, you are using it in aBoolean context . In aBoolean context, any value is taken as either true or false. As wediscussed earlier, any non-zero number or non-empty string, tuple,list, or dictionary evaluates as true. Zero (of any numeric type),None , and empty strings, tuples, lists, anddictionaries evaluate as false. When you want to test a valuex in a Boolean context, use the followingcoding style:
This is the clearest and most Pythonic form. Don’tuse:
There is a crucial difference between saying that an expression“returns
True '(meaning the expression returns the value 1 intended as a Boolean result) and saying that an expression“evaluates as true” (meaning theexpression returns any result that is true in a Boolean context).When testing an expression, you care about the latter condition, notthe former.
If the expression for the
if clause evaluates astrue, the statements following the if clauseexecute, and the entire if statement ends.Otherwise, the expressions for any elif clausesare evaluated in order. The statements following the firstelif clause whose condition is true, if any, areexecuted, and the entire if statement ends.Otherwise, if an else clause exists, thestatements following it are executed.
The
while statement in Python supports repeated execution of a statement orblock of statements that is controlled by a conditional expression.Here’s the syntax for the while statement:
A
while statement can also include anelse clause and break andcontinue statements, as we’lldiscuss shortly.
Here’s a typical
while statement:
First,
expression , which is known as theloop condition , isevaluated. If the condition is false, the while statement ends. If the loop condition is satisfied, the statement orstatements that comprise the loop body are executed. When the loop body finishesexecuting, the loop condition is evaluated again, to see if anotheriteration should be performed. This process continues until the loopcondition is false, at which point the while statement ends.
The loop body should contain code that eventually makes the loopcondition false, or the loop will never end unless an exception israised or the loop body executes a
break statement. A loop that is in a function’s body alsoends if a return statement executes in the loopbody, as the whole function ends in this case.
The
for statementin Python supports repeated execution of a statement or block ofstatements that is controlled by an iterable expression.Here’s the syntax for the for statement:
Note that the
in keyword is part of the syntax ofthe for statement and is functionally unrelated tothe in operator used for membership testing. Afor statement can also include anelse clause and break andcontinue statements, as we’lldiscuss shortly.
Here’s a typical
for statement:
iterable may be any Python expressionsuitable as an argument to built-in function iter ,which returns an iterator object (explained in detail in the nextsection). target is normally an identifierthat names the control variable of the loop; the for statement successively rebinds this variable to each item of theiterator, in order. The statement or statements that comprise theloop body execute once foreach item in iterable (unless the loopends because an exception is raised or a break orreturn statement isexecuted).
A target with multiple identifiers is also allowed, as with anunpacking assignment. In this case, the iterator’sitems must then be sequences, each with the same length, equal to thenumber of identifiers in the target. For example, when
d is a dictionary, this is a typical wayto loop on the items in d :
The
items method returns a list of key/valuepairs, so we can use a for loop with twoidentifiers in the target to unpack each item intokey and value .
If the iterator has a mutable underlying object, that object must notbe altered while a
for loop is in progress on it.For example, the previous example cannot useiteritems instead of items .iteritems returns an iterator whose underlyingobject is d , so therefore the loop body cannotmutate d (by del d[key] ). items returns a list,though, so d is not the underlying object of theiterator and the loop body can mutate d .
The control variable may be rebound in the loop body, but is reboundagain to the next item in the iterator at the next iteration of theloop. The loop body does not execute at all if the iterator yields noitems. In this case, the control variable is not bound or rebound inany way by the
for statement. If the iteratoryields at least one item, however, when the loop statementterminates, the control variable remains bound to the last value towhich the loop statement has bound it. The following code is thuscorrect, as long as someseq is not empty:
An
iterator is any objecti such that you can calli .next( ) without anyarguments. i .next( ) returns the next item of iterator i , or,when iterator i has no more items, raisesa StopIteration exception. When you write a class(see Chapter 5), you can allow instances of theclass to be iterators by defining such a methodnext . Most iterators are built by implicit orexplicit calls to built-in function iter , coveredin Chapter 8. Calling a generator also returns aniterator, as we’ll discuss later in thischapter.
The
for statement implicitly callsiter to get an iterator. The following statement:
is equivalent to:
Thus, if
iter( c ) returns an iterator i such thati .next( ) never raisesStopIteration (an infinite iterator ), the loop for x in c : never terminates(unless the statements in the loop body contain suitablebreak or return statements orpropagate exceptions).iter( c ) ,in turn, calls special method c .__iter__( ) to obtain and return an iterator onc . We’ll talk more aboutthe special method __iter__ in Chapter 5.
Iterators were first introduced in Python 2.2. In earlier versions,
for x in S : requiredS to be a sequence that was indexable withprogressively larger indices 0 ,1 , .., and raised anIndexError when indexed with a too-large index.Thanks to iterators, the for statement can now beused on a container that is not a sequence, such as a dictionary, aslong as the container is iterable (i.e., it defines an __iter__ special method so that functioniter can accept the container as the argument andreturn an iterator on the container). Built-in functions that used torequire a sequence argument now also accept any iterable.
Looping over a sequence of integersis a common task, so Python provides built-in functions
range and xrange to generateand return integer sequences. The simplest, most idiomatic way toloop n times in Pythonis:
range( x ) returns a list whose items are consecutive integers from0 (included) up to x (excluded).range( x ,y ) returns a list whose items are consecutive integers fromx (included) up toy (excluded). The result is the empty listif x is greater than or equal toy .range( x ,y ,step ) returns a list of integers from x (included) up to y (excluded), such thatthe difference between each two adjacent items in the list isstep . If step is less than 0 , range countsdown from x toy . range returns theempty list when x is greater than or equalto y and step is greater than0 , or when x is lessthan or equal to y andstep is less than 0 . Ifstep equals 0 ,range raises an exception.
While
range returns a normal list object, usablefor all purposes, xrange returns a special-purposeobject, specifically intended to be used in iterations like thefor statement shown previously.xrange consumes less memory thanrange for this specific use. Leaving aside memoryconsumption, you can use range wherever you coulduse xrange .
Acommon use of a
for loop is to inspect each itemin a sequence and build a new list by appending the results of anexpression computed on some or all of the items inspected. Theexpression form, called a list comprehension , lets you code this common idiomconcisely and directly. Since a list comprehension is an expression(rather than a block of statements), you can use it directly whereveryou need an expression (e.g., as an actual argument in a functioncall, in a return statement, or as a subexpressionfor some other expression).
A list comprehension has the following syntax:
target anditerable are the same as in a regularfor statement. You must enclose theexpression in parentheses if it indicatesa tuple.
lc-clauses is a series of zero or moreclauses, each with one of the following forms:
target anditerable in each for clause of a list comprehension have the same syntax as those in aregular for statement, and theexpression in each if clause of a list comprehension has the same syntax as theexpression in a regularif statement.
A list comprehension is equivalent to a
for loopthat builds the same list by repeated calls to the resultinglist’s append method. For example(assigning the list comprehension result to a variable for clarity):
is the same as the
for loop:
Here’s a list comprehension that uses an
if clause:
which is the same as a
for loop that contains anif statement:
And here’s a list comprehension that uses a
for clause:
which is the same as a
for loop with anotherfor loop nested inside:
As these examples show, the order of
for andif in a list comprehension is the same as in theequivalent loop, but in the list comprehension the nesting staysimplicit.
The
break statement is allowed only inside a loop body. Whenbreak executes, the loop terminates. If a loop isnested inside other loops, break terminates onlythe innermost nested loop. In practical use, abreak statement is usually inside some clause ofan if statement in the loop body so that itexecutes conditionally.
One common use of
break is in the implementationof a loop that decides if it should keep looping only in the middleof each loop iteration:
The
continue statement is allowed only inside a loop body. Whencontinue executes, the current iteration of theloop body terminates, and execution continues with the next iterationof the loop. In practical use, a continue statement is usually inside some clause of an if statement in the loop body so that it executes conditionally.
The
continue statement can be used in place of deeplynested if statements within a loop. For example:
This equivalent code does conditional processing without
continue :
Both versions function identically, so which one you use is a matterof personal preference.
Boththe
while and for statementsmay optionally have a trailing else clause. Thestatement or statements after the else executewhen the loop terminates naturally (at the end of thefor iterator or when the while loop condition becomes false), but not when the loop terminatesprematurely (via break , return ,or an exception). When a loop contains one or morebreak statements, you often need to check whetherthe loop terminates naturally or prematurely. You can use anelse clause on the loop for this purpose:
The body of a Python compoundstatement cannot be empty—it must contain at least onestatement. The
pass statement, which performs noaction, can be used as a placeholder when a statement issyntactically required but you have nothing specific to do.Here’s an example of using pass in a conditional statement as a part of somewhat convoluted logic,with mutually exclusive conditions being tested:
Python supports exception handlingwith the
try statement, which includestry , except ,finally , and else clauses. Aprogram can explicitly raise an exception with theraise statement. As we’ll discussin detail in Chapter 6, when an exception israised, normal control flow of the program stops and Python looks fora suitable exception handler.
Active2 months ago
Flow Of Execution Python Download
Wireshark loopback adapter. Possible Duplicate:
Terminating a Python script
I have a simple Python script that I want to stop executing if a condition is met.
For example:
Essentially, I am looking for something that behaves equivalently to the 'return' keyword in the body of a function which allows the flow of the code to exit the function and not execute the remaining code.
Community♦
Ray VegaRay Vega
86.3k9292 gold badges203203 silver badges195195 bronze badges
marked as duplicate by Mark Byers, Michael Mrozek, danben, gnovice, sthAug 1 '10 at 18:04
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
8 Answers
To exit a script you can use,
You can also provide an exit status value, usually an integer.
Exits with zero, which is generally interpreted as success. Non-zero codes are usually treated as errors. The default is to exit with zero.
Prints 'aa! errors!' and exits with a status code of 1.
There is also an _exit() function in the os module. The sys.exit() function raises a SystemExit exception to exit the program, so try statements and cleanup code can execute. The os._exit() version doesn't do this. It just ends the program without doing any cleanup or flushing output buffers, so it shouldn't normally be used.
The Python docs indicate that os._exit() is the normal way to end a child process created with a call to os.fork(), so it does have a use in certain circumstances.
Matthew Strawbridge
15.7k1010 gold badges5454 silver badges8383 bronze badges
ryan_sryan_s
5,81133 gold badges2424 silver badges2727 bronze badges
gimelgimel
61.8k1010 gold badges6464 silver badges9999 bronze badges
You could put the body of your script into a function and then you could return from that function.
David LockeDavid Locke
10k88 gold badges2929 silver badges5050 bronze badges
You can either use:
or:
The optional parameter can be an exit code or an error message. Both methods are identical. I used to prefer sys.exit, but I've lately switched to raising SystemExit, because it seems to stand out better among the rest of the code (due to the raise keyword).
12.3k55 gold badges2525 silver badges3535 bronze badges
SecSec
4,27255 gold badges2626 silver badges5353 bronze badges
DanaDana
21k1616 gold badges5454 silver badges7171 bronze badges
Try
Flow Of Execution Python Definition
It is like the perl
if this is what you are looking for. It terminates the execution of the script even it is called from an imported module / def /function
GabrieleVGabrieleV
1,87822 gold badges1313 silver badges88 bronze badges
If the entire program should stop use sys.exit() otherwise just use an empty return.
AndréAndré
10.3k33 gold badges2929 silver badges4242 bronze badges
Not the answer you're looking for? Browse other questions tagged pythonsyntaxscriptingexit or ask your own question.Comments are closed.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |