As with most imperative languages, there are three main categories of program control flow:
Function calls are covered in thenext section.
Generators and list comprehensions are advanced forms of program control flow, but they are not covered here.
Control flow in Python at a glance:
x=-6# Branchingifx>0:# Ifprint("Positive")elifx==0:# Else if AKA elseifprint("Zero")else:# Elseprint("Negative")list1=[100,200,300]foriinlist1:print(i)# A for loopforiinrange(0,5):print(i)# A for loop from 0 to 4foriinrange(5,0,-1):print(i)# A for loop from 5 to 1foriinrange(0,5,2):print(i)# A for loop from 0 to 4, step 2list2=[(1,1),(2,4),(3,9)]forx,xsqinlist2:print(x,xsq)# A for loop with a two-tuple as its iteratorl1=[1,2];l2=['a','b']fori1,i2inzip(l1,l2):print(i1,i2)# A for loop iterating two lists at once.i=5whilei>0:# A while loopi-=1list1=["cat","dog","mouse"]i=-1# -1 if not foundforiteminlist1:i+=1ifitem=="dog":break# Break; also usable with while loopprint("Index of dog:",i)foriinrange(1,6):ifi<=4:continue# Continue; also usable with while loopprint("Greater than 4:",i)
In Python, there are two kinds of loops, 'for' loops and 'while' loops.
A for loop iterates over elements of a sequence (tuple or list). A variable is created to represent the object in the sequence. For example,
x=[100,200,300]foriinx:print(i)
This will output
100200300
Thefor
loop loops over each of the elements of a list or iterator, assigning the current element to the variable name given. In the example above, each of the elements inx
is assigned toi
.
A built-in function called range exists to make creating sequential lists such as the one above easier. The loop above is equivalent to:
l=range(100,301,100)foriinl:print(i)
Similar to the slicing operation, in the range function, the first argument is the starting integer (we can just pass one argument to the range, which will be interpreted as thesecond argument, and then the default value: 0 is used for the first argument), and the second argument is the ending integerbut excluded from the list.
>>>range(5)range(0,5)>>>list(range(5))#need to use list() to really print the list out[0,1,2,3,4]>>>set(range(5))#we can also print a set out{0,1,2,3,4}>>>list(range(1,5))[1,2,3,4]>>>list(range(1,1))#starting from 1, but 1 itself is excluded from the list[]
The next example uses a negativestep (the third argument for the built-in range function, which is similar to the slicing operation):
foriinrange(5,0,-1):print(i)
This will output
54321
The negative step can be -2:
foriinrange(10,0,-2):print(i)
This will output
108642
For loops can have names for each element of a tuple, if it loops over a sequence of tuples:
l=[(1,1),(2,4),(3,9),(4,16),(5,25)]forx,xsquaredinl:print(x,':',xsquared)
This will output
1 : 12 : 43 : 94 : 165 : 25
Links:
A while loop repeats a sequence of statements until the condition becomes false. For example:
x=5whilex>0:print(x)x=x-1
Will output:
54321
Python's while loops can also have an 'else' clause, which is a block of statements that is executed (once) when the while condition evaluates to false. The break statement (see the next section) inside the while loop will not direct the program flow to the else clause. For example:
x=5y=xwhiley>0:print(y)y=y-1else:print(x)
This will output:
543215
Unlike some languages, there is no post-condition loop.
When the while condition never evaluates to false, i.e., is always true, then we have aninfinite loop. For example,
x=1whilex>0:print(x)x+=1
This results in an infinite loop, which prints 1,2,3,4,... . To stop an infinite loop, we need to use the break statement.
Links:
Python includes statements to exit a loop (either a for loop or a while loop) prematurely. To exit a loop, use the break statement:
x=5whilex>0:print(x)breakx-=1print(x)
This will output
5
The statement to begin the next iteration of the loop without waiting for the end of the current loop is 'continue'.
l=[5,6,7]forxinl:continueprint(x)
This will not produce any output.
The else clause of loops will be executed if no break statements are met in the loop.
l=range(1,100)forxinl:ifx==100:print(x)breakelse:print(x," is not 100")else:print("100 not found in range")
Another example of a while loop using the break statement and the else statement:
expected_str="melon"received_str="apple"basket=["banana","grapes","strawberry","melon","orange"]x=0step=int(raw_input("Input iteration step: "))whilereceived_str!=expected_str:ifx>=len(basket):print("No more fruits left on the basket.");breakreceived_str=basket[x]x+=step# Change this to 3 to make the while statement# evaluate to false, avoiding the break statement, using the else clause.ifreceived_str==basket[2]:print("I hate",basket[2],"!");breakifreceived_str!=expected_str:print("I am waiting for my ",expected_str,".")else:print("Finally got what I wanted! my precious ",expected_str,"!")print("Going back home now !")
This will output:
Input iteration step: 2I am waiting for my melon .I hate strawberry !Going back home now !
Python determines where a loop repeats itself by the indentation in the whitespace. Everything that is indented is part of the loop, the next entry that is not indented is not. For example, the code below prints "1 1 2 1 1 2"
foriin[0,1]:forjin["a","b"]:print("1")print("2")
On the other hand, the code below prints "1 2 1 2 1 2 1 2"
foriin[0,1]:forjin["a","b"]:print("1")print("2")
There is basically only one kind of branch in Python, the 'if' statement. The simplest form of the if statement simple executes a block of code only if a given predicate is true, and skips over it if the predicate is false
For instance,
>>>x=10>>>ifx>0:...print("Positive")...Positive>>>ifx<0:...print("Negative")...
You can also add "elif" (short for "else if") branches onto the if statement. If the predicate on the first “if” is false, it will test the predicate on the first elif, and run that branch if it’s true. If the first elif is false, it tries the second one, and so on. Note, however, that it will stop checking branches as soon as it finds a true predicate, and skip the rest of the if statement. You can also end your if statements with an "else" branch. If none of the other branches are executed, then python will run this branch.
>>>x=-6>>>ifx>0:...print("Positive")...elifx==0:...print("Zero")...else:...print("Negative")...'Negative'
Links:
Any of these loops, branches, and function calls can be nested in any way desired. A loop can loop over a loop, a branch can branch again, and a function can call other functions, or even call itself.
123246369
123------1|1232|2463|369