Flow control

In programming, flow control represents the order in which the commands are executed. For flow control, we use control structures that provide execution of code blocks under certain conditions.
 
In Python we have two types of control structures:
conditional structures
loops

Conditional structures

Conditional structures provide execution of some part(s) of the program if the condition(s) are met.
Conditions are defined with the keyword if, followed by a conditional expression (let’s name it exp), which returns a boolean type value. If the result of exp is True, we execute a code block behind the colon character ( : ).
>>> x = input()
4
>>> if x < 5: #conditional expression (exp) is x < 5
        x *= 2 #code block which is executed if exp is True
        print(x)
8

There is another case of the if-structure, consisting of if and else blocks. If the result of exp in the if-block is False, we execute the else-block, which is after the keyword else. Now we have two branches of our program flow and whether it goes by the first or second branch, depends on the result of our conditional expression (exp).

>>> x = input()
10
>>> if a < 5:
        print("First branch of flow")
    else:
        print("Second branch of flow")
'Second branch of flow'

If-else structure can also perform like a ternary operator (?: from C++), which doesn’t exist currently in Python. This is how it works:

exp_1 if condition else exp_2

If condition is True, exp_1 will be executed. If condition is false, exp_2 will be executed.

Here’s an example:

>>> x = 12 
>>> y = 5 if x % 2 != 0 else 7
>>> print y
>>> #condition is false, so we execute second command, which gives variable x a value 7
The most complex case of if-structure is when we have multiple conditional expressions (exp1, exp2, etc.) in our program. In that case, for every exp we have branching of our program flow, which will keep branching until the first exp result is True. For every branching except the first and the last one, we use the keyword elif to define a new conditional expression. For the last branching, we use the keyword else. Elif has the same role as if, the only difference being if is used for the first branching and elif is used for all other branchings between if and else.
 
Here’s an example if you didn’t quite get it. We will write a program that tells us which grade did we score on the exam, based on a number of points, which will be our input variable.
>>> grade = 0; #we have to initialize this variable, which will be our grade 
>>> points = input("Points scored: ") #this represents the number of points we scored; we define it
65
>>> if (points > 100) or (points < 0): 
        print("Inproper input.")
    elif points > 90:
        grade = 10        
        print("Final grade is", grade,".")
    elif points > 80:
        grade = 9
        print("Final grade is", grade,".")
    elif points > 70:
        grade = 8
        print("Final grade is", grade,".")
    elif points > 60:
        grade = 7
        print("Final grade is", grade,".")
    elif points > 50:
        grade = 6
        print("Final grade is", grade,".")
    else:
        grade = 5
        print("Final grade is", grade,". Student failed.")
Final grade is 7.

Loops

In programming, loops are conditional iterative statements which are usually used when we want to execute the same blocks of code multiple number of times.
There are two types of loops:
for loop
while loop

For loops

In Python, for loops are used for iteration over a sequence. A sequence can be a string, list, range, tuple, dictionary or a set. For loops are defined by the keyword for, followed by expression i in seq, where i is our iterator and seq is our sequence. That expression represents the membership operation (chapter 3) and returns bool value as a result after every iteration. If the result is True, code block in scope of our loop will be executed, otherwise, we leave the loop.
This is structure of a for loop:
for i in seq: 
        code_block 

Let’s try and calculate an average grade after the exam if we have the grades of all students. We will presume that every student passed the exam.

>>> grades = [6, 7, 7, 7, 8, 8, 8, 8, 9, 9, 10] #grades of all students
>>> sum = 0 #sum of all grades
>>> n = 0 #number of students; we will calculate it by iteration
>>> avg = 0 #average grade
>>> for i in grades:
        sum += i
        n += 1
>>> avg = sum / n
>>> print("Average grade is ", avg, ".")
'Average grade is  7.909090909090909.'

While loops

While loops are different from for loops, because they execute code block as long as the condition is True. While loops are defined by the keyword while, followed by a conditional expression, which returns a boolean value. As we said, if that value is True, the code block in the scope of our loop will be executed. When the value becomes False, we will leave the loop.
This is the structure of a while loop:
while condition:
        code_block

Let’s try and sum first 100 integer numbers using a while loop.

>>> num = 1 #starting number, which is 1
>>> sum = 0 #sum, initialized with 0
>>> while num <= 100: 
        sum += num
        num += 1
>>> print(sum)
5050

Execution control in loops

In some situations, we may want to leave a loop before our iterator reaches the end of the sequence (for loops), or before our condition becomes False (while loops). We can use the command break, which tells the program we want to exit the loop we’re currently in. After we leave the loop, we continue with the execution of the rest of the program which comes after the loop we just left.
Command break is very useful because it enables us to create infinite loops in case we don’t know in advance how many iterations we need to do in order to execute code block.
 
Let’s write a program which will count how many times we failed the exam, based on the number of points we read from standard input:
>>> n = 0 #fail count :')
>>> while True: 
        points = input("Points scored: ")
        if int(points) < 51:
            print("You fail.")
            n += 1
        else:
            print("You pass.")
            break

Points scored: 12
You fail.
Points scored: 35
You fail.
Points scored: 50
You fail.
Points scored: 61
You pass.
>>> print(n)
3
>>> """
    We defined an infinite loop because we don't know how many times it will take until the student
    passes the exam. The only way to exit a loop is via the break command, which will be executed at
    the moment the student passes, which is when the variable points is 51 or higher. When we read
    in 12, 35 and 50,  the student failed the exam and the number of fails (n) gets incremented each
    time. When we read in 61, the student passed and we exited the loop.
"""
Opposite of the command break is the command continue, which tells the program to skip the rest of the code block inside of loop. Program proceeds with the next iteration afterwards.
 
Let’s write a program which counts the number of Pokemon encounters until we find Gengar. From the standard input we will read the name of the Pokemon and, if it’s not Gengar, we continue with our inputs.
>>> cnt = 0
>>> while True:
        pokemon = input("Who's that Pokemon? ")
        if pokemon != "Gengar":
            cnt += 1
            continue
        else:
            print("Oh no! A wild Gengar fled! :(\n", cnt, " encounters \n" )
            break

Who's that Pokemon? Venusaur
Who's that Pokemon? Pidgeot
Who's that Pokemon? Dragonite
Who's that Pokemon? Lapras
Who's that Pokemon? Arcanine
Who's that Pokemon? Gengar
Oh no! A wild Gengar fled! :(
 5 encounters

>>> """
    Similar to the previous example, we define an infinite while loop because we don't know in
    advance how many Pokemon we will encounter before Gengar. When we encounter a Pokemon which is
    not Gengar, we procceed to the next iteration and increment our number of encounters. When we
    find Gengar, we exit the loop and print how many Pokemon encounters we had.
    Maybe we didn't catch Gengar this time, but we definitely completed this task correctly! 
"""
Sometimes, we don’t need to execute any commands, but we can’t just leave an empty space, because the program will signal an error then. For that cause, we can use the keyword pass, which means we proceed to the next line in our program flow. Pass is basically a command which executes, but nothing happens, in other words, null command.
 
Let’s write a program that wakes up a passenger on his trip from Belgrade to Barcelona, with multiple stops on the road.
>>> dest = None
>>> stops_cnt = 0 #number of stops on the road
>>> for i in ["Belgrade", "Zagreb", "Ljubljana", "", "Torino", "Marseille", "Barcelona"]:
        if i != "Barcelona":
            pass
            stops_cnt += 1
        else:
            dest = i
            print("Wake up, you've arrived to", dest, ".")
            break
>>> print(stops_cnt)
5
>>>'''
    As we can see, when executed, command pass does nothing. After its execution, program executes
    the next line of code, in this case increments the number of stops on the road. Just to be
    sure our command after the pass executed, we're going to print a value of stops_cnt, which is
    5 and a proof that we succesfully completed this task.
'''

Table of contents

Leave a Reply