Mahmoud Abdullah

Oct 10, 20214 min

Control Flow in Python

Python has several built-in keywords for conditional logic, loops, and other standard control flow concepts found in other programming languages.

if, elif, and else

The if statement is one of the most well-known control flow statement types. It checks a condition that, if True, evaluates the code in the block that follows:

if x < 0:
 
print('It's negative')

An if statement can be optionally followed by one or more elif blocks and a catch-all else block if all of the conditions are False:

if x < 0:
 
print('It's negative')
 
elif x == 0:
 
print('Equal to zero')
 
elif 0 < x < 5:
 
print('Positive but smaller than 5')
 
else:
 
print('Positive and larger than or equal to 5')

If any of the conditions is True, no further elif or else blocks will be reached. With a compound condition using and or or, conditions are evaluated left to right and will short-circuit:

>>> a = 5; b = 7
 
>>> c = 8; d = 4 46 |
 
>>> if a < b or c > d:
 
... print('Made it')
 
comparisonMade it

In this example, the comparison c > d never gets evaluated because the first comparison was True. It is also possible to chain comparisons:

>>> 4 > 3 > 2 > 1
 
True


for loops

for loops are for iterating over a collection (like a list or tuple) or an iterator. The standard syntax for a for loop is:

for value in collection:
 
# do something with value

You can advance a for loop to the next iteration, skipping the remainder of the block, using the continue keyword. Consider this code, which sums up integers in a list and skips None values:

sequence = [1, 2, None, 4, None, 5]
 
total = 0
 
for value in sequence:
 
if value is None:
 
continue
 
total += value

A for loop can be exited altogether with the break keyword. This code sums ele‐ ments of the list until a 5 is reached:

sequence = [1, 2, 0, 4, 6, 5, 2, 1]
 
total_until_5 = 0
 
for value in sequence:
 
if value == 5:
 
break
 
total_until_5 += value

The break keyword only terminates the innermost for loop; any outer for loops will continue to run:

>>> for i in range(4):
 
... for j in range(4):
 
... if j > i:
 
... break
 
... print((i, j))
 
(0, 0)
 
(1, 0)
 
(1, 1)
 
(2, 0)
 
(2, 1)
 
(2, 2)
 
(3, 0)
 
(3, 1)
 
(3, 2)
 
(3, 3)

As we will see in more detail, if the elements in the collection or iterator are sequen‐ ces (tuples or lists, say), they can be conveniently unpacked into variables in the for loop statement: for a, b, c in iterator: # do something


while loops

A while loop specifies a condition and a block of code that is to be executed until the condition evaluates to False or the loop is explicitly ended with break:

x = 256
 
total = 0
 
while x > 0:
 
if total > 500:
 
break
 
total += x
 
x = x // 2


pass

pass is the “no-op” statement in Python. It can be used in blocks where no action is to be taken (or as a placeholder for code not yet implemented); it is only required because Python uses whitespace to delimit blocks:

if x < 0:
 
print('negative!')
 
elif x == 0:
 
# TODO: put something smart here
 
pass
 
else:
 
print('positive!')


range

The range function returns an iterator that yields a sequence of evenly spaced integers:

range(10)
 
range(0, 10)
 
>>> list(range(10))
 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Both a start, end, and step (which may be negative) can be given:

>>> list(range(0, 20, 2))
 
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
 
>>> list(range(5, 0, -1))
 
[5, 4, 3, 2, 1]

As you can see, range produces integers up to but not including the endpoint. A common use of range is for iterating through sequences by index:

seq = [1, 2, 3, 4]
 
for i in range(len(seq)):
 
val = seq[i]

While you can use functions like list to store all the integers generated by range in some other data structure, often the default iterator form will be what you want. This snippet sums all numbers from 0 to 99,999 that are multiples of 3 or 5:

sum = 0
 
for i in range(100000):
 
# % is the modulo operator
 
if i % 3 == 0 or i % 5 == 0:
 
sum += i

While the range generated can be arbitrarily large, the memory use at any given time may be very small.


Ternary expressions

A ternary expression in Python allows you to combine an if-else block that pro‐ duces a value into a single line or expression. The syntax for this in Python is:

value = true-expr if condition else false-expr

Here, true-expr and false-expr can be any Python expressions. It has the identical effect as the more verbose:

if condition:
 
value = true-expr
 
else:
 
value = false-expr

This is a more concrete example:

>>> x = 5
 
>>> 'Non-negative' if x >= 0 else 'Negative'
 
'Non-negative'

As with if-else blocks, only one of the expressions will be executed. Thus, the “if ” and “else” sides of the ternary expression could contain costly computations, but only the true branch is ever evaluated. While it may be tempting to always use ternary expressions to condense your code, realize that you may sacrifice readability if the condition, as well as the true and false expressions, are very complex


References:

    1