Skip to content

3. Control Flow

Similar to how you would read a script, Python reads in a top-down order. You, the scriptwriter, are able to control how Python reads and execute the script.

This is achieved using control flow statements. There are 3 common control flow statements in Python,

  1. if
  2. for
  3. while

The if Statement

Simply put, if a certain condition is true, Python runs the block of statement in the if-block, else it runs the statements in the else-block. The else clause is optional.

grade = int(input('Enter your grade: '))

if grades >= 85:
    print('Great job!')
elif grades >= 50:
    print('Study harder!')
else:
    print('Hello! Wake up!')

There is also the special operator in which we can use to check if an element is in a string, list, or dictionary. What does the following program print?

my_list = [1, 2, 3, 4]
my_dict = {'two': 2, 'four': 4}
if 2 not in my_list:
    print("hi")
elif 2 in my_dict:
    print("hello")
elif 1 in my_dict:
    print("hallo")
else:
    print("hey")

The for Statement

A for loop allows the programmer to iterate over a sequence of objects.

for i in range(1,5):
    print(i)
print('End')

Output

1
2
3
4
End

It can also be use to iterate through a list.

my_pets = ['lions', 'tigers', 'eagles', 'crocs']

for pet in my_pets:
    print(pet)

Output

lions
tigers
eagles
crocs

Let's now try writing a program to find the average of the values in a list.

my_list = [1, 2, 3, 4]
total = 0
for x in my_list:
    total = total + x
result = total / len(my_list)
print(result)