Open In Colab

3 : Control Structures#

In the programming world, there are 3 main control structures to create algorithms.

  • The If / Else alternatives

  • The For loops

  • The While loops

1. Alternatives If / Else :#

This structure allows to test a sequence of alternatives. If a condition is met, then the instructions that follow it are executed and the control structure is stopped, otherwise the next condition is tested.

def test_of_sign(value):
  if value < 0:
    print('negative')
  elif value == 0:
    print('null')
  else:
    print('positive')

test_of_sign(-2)
negative

Important note : A condition is met if and only if it matches the result bolean True.

value = -2
print(value < 0) # the result of this comparison is True

if value < 0:
  print('negative')
True
negative

This allows you to develop algorithms with mixtures of Logic operations and comparison operations. For example : if the weather is nice and warm, then I will go swimming

x = 3
y = -1
if (x>0) and (y>0):
  print('x and y are positive')
else:
  print('x and y are not both positive')
x and y are not both positive

2. For loop#

A for loop allows you to create iterative algorithms (that perform a certain task several times in a row). For that, the loop goes through all the elements of a so-called iterable object. It can be a list, a dictionary, a range, a numpy array, or many other objects…

# range(start, end, step) is a very useful built-in function of python that returns an iterable.
for i in range(0, 10):
    print(i)
0
1
2
3
4
5
6
7
8
9
# we can have fun combining this loop with our function from earlier.
for i in range(-10, 10, 2):
    print(i)
    test_of_sign(i)
-10
negative
-8
negative
-6
negative
-4
negative
-2
negative
0
null
2
positive
4
positive
6
positive
8
positive

3. While loop#

A While loop allows to perform an action in loop, as long as the execution condition is validated (as long as the condition is True)

x = 0
while x < 10:
  print(x)
  x += 1 # increments x by 1 (equivalent to x = x+1)
0
1
2
3
4
5
6
7
8
9

4. exercise and solution#

Implement the Fibonacci sequence [0, 1, 1, 2, 3, 5, 8, 13, 21, …] that starts from 2 numbers a=0 and b=1, and computes the next number by adding the previous 2 numbers.

Hints:

  • For this exercise you will need a While ball

  • You can print this sequence until you reach a number n that you choose

  • in python it is possible to update 2 variables simultaneously on the same line: a, b = b, a+b

Solution#

def fibonacci(n):
    # return a list containing the fibonacci sequence until n
    a = 0
    b = 1
    while b < n:
      a, b = b, a+b
      print(a)

fibonacci(1000)
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987