So far we have encountered variables, basic data types (such as int, float, string, bool) and more complex data structures (list, dictionaries, etc.)
So far we have encountered variables, basic data types (such as int, float, string, bool) and more complex data structures (list, dictionaries, etc.)
In order to write some programs, we would need to check for conditions and then act accordingly whether or not a condition is met, or perform some calculations repeatedly.
In order to write some programs, we would need to check for conditions and then act accordingly whether or not a condition is met, or perform some calculations repeatedly.
Therefore, we now look at elements how to control the flow of our programs:
Therefore, we now look at elements how to control the flow of our programs:
*```if``` statements
*```if``` statements
*```for``` loops
*```for``` loops
*``` while``` loops
*``` while``` loops
* iterating over lists or dictionaries, etc.
* iterating over lists or dictionaries, etc.
## Checking for conditions
## Checking for conditions
### If statement
### If statement
The ``if`` statement is the simplest way to conditionally execute some code (or not).
The ``if`` statement is the simplest way to conditionally execute some code (or not).
The general syntax is:
The general syntax is:
```
```
if condition:
if condition:
action
action
```
```
The ```condition``` needs to evaluate to either ```True``` or ```False```, i.e. a boolean value.
The ```condition``` needs to evaluate to either ```True``` or ```False```, i.e. a boolean value.
The fundamental checks are for some variables ```a``` and ```b```:
The fundamental checks are for some variables ```a``` and ```b```:
* Equal: ```a == b```.
* Equal: ```a == b```.
Note the double ``` ==``` : a single ```=``` is used for assignments, so we need to use the double ```==``` for a comparison
Note the double ``` ==``` : a single ```=``` is used for assignments, so we need to use the double ```==``` for a comparison
* not equal: ``` a != b```
* not equal: ``` a != b```
* less than: ```a < b``` or less equal ``` a <= b ```
* less than: ```a < b``` or less equal ``` a <= b ```
* greater than: ``` a > b``` or greater equal ``` a >= b```
* greater than: ``` a > b``` or greater equal ``` a >= b```
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
a=1
a=1
b=2
b=2
# First we can look what the condition might be:
# First we can look what the condition might be:
print (a>b)
print (a>b)
# now do a conditional:
# now do a conditional:
ifa>b:
ifa>b:
print('a is greater than b')
print('a is greater than b')
print('--------')
print('--------')
```
```
%% Output
%% Output
False
False
--------
--------
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
... where we note that the statement in the conditional was not executed.
... where we note that the statement in the conditional was not executed.
We also note a key concept in python: The code in the conditional statement is *** indented ***. Unlike other programming languages, python does not use, for example, brackets to indicte which parts of the code belong together but indentations.
We also note a key concept in python: The code in the conditional statement is *** indented ***. Unlike other programming languages, python does not use, for example, brackets to indicte which parts of the code belong together but indentations.
> **Note**
> **Note**
>
>
> Code that belongs together has the same level of indentation.
> Code that belongs together has the same level of indentation.
This has the benefit that the code is much more readable as it forces us to write the code such that parts of the code that belong together also have the same level of indentation. It is also a source of confusing bugs if we accidently get the indentation wrong...
This has the benefit that the code is much more readable as it forces us to write the code such that parts of the code that belong together also have the same level of indentation. It is also a source of confusing bugs if we accidently get the indentation wrong...
To be more flexible, we can test for more than one condition using ```elif``` (else-if) and then finally ```else``` as a "catch-all" for all conditions that we have not met so far.
To be more flexible, we can test for more than one condition using ```elif``` (else-if) and then finally ```else``` as a "catch-all" for all conditions that we have not met so far.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
a=10
a=10
ifa>100:
ifa>100:
print ('a is greater than 100')
print ('a is greater than 100')
elifa>50:
elifa>50:
print ('a is greater than 50')
print ('a is greater than 50')
elifa>10:
elifa>10:
print ('a is greater than 10')
print ('a is greater than 10')
else:
else:
print ('none applies')
print ('none applies')
```
```
%% Output
%% Output
none applies
none applies
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
# if we only have one condition to test, we can write a short one-liner
# if we only have one condition to test, we can write a short one-liner
a=1
a=1
b=2
b=2
print ('a is greater than b')ifa>belseprint ('b is greater than a')
print ('a is greater than b')ifa>belseprint ('b is greater than a')
```
```
%% Output
%% Output
b greater than a
b greater than a
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
We can also have more than one condition and combine them using ```and``` , ```or```.
We can also have more than one condition and combine them using ```and``` , ```or```.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
a=10
a=10
b=15
b=15
if (a>10)and(b<20):
if (a>10)and(b<20):
print('condition met')
print('condition met')
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
We can also nest ```if``` statements, i.e. have ```if``` statements within ```if``` statements.
We can also nest ```if``` statements, i.e. have ```if``` statements within ```if``` statements.
**Exercise**
**Exercise**
Write a nested ```if``` statement checking if the value of the variable ```a``` is above 25, and if yes, if it is also above 30 or not.
Write a nested ```if``` statement checking if the value of the variable ```a``` is above 25, and if yes, if it is also above 30 or not.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
a=27
a=27
# ... your code here ...
# ... your code here ...
ifa>25:
print ('a is greater than 25')
ifa>30:
print('a is greater than 30')
else:
print('a is not greater than 30')
```
```
%% Output
a is greater than 25
a is not greater than 30
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
---
---
## for loops
## for loops
Quite often we want to execute the same code a fixed number of times. For example, we want to execute the code five times or we want to look at all elements of a list, a dictionary or even a string.
Quite often we want to execute the same code a fixed number of times. For example, we want to execute the code five times or we want to look at all elements of a list, a dictionary or even a string.
In this case, we can use the ```for``` loop.
In this case, we can use the ```for``` loop.
The general syntax is
The general syntax is
```
```
for variable in list:
for variable in list:
do something
do something
else:
else:
do something else
do something else
```
```
(where typically we do not need the ```else``` statement.)
(where typically we do not need the ```else``` statement.)
Again, note the indentations that define which part of the code belongs together.
Again, note the indentations that define which part of the code belongs together.
If we want to run the code a certain number of times, we can use the ```range(start, stop, step)``` function, where ```start``` specifies the number we want to start from, ```stop``` the final number (excluding this value) and ```step``` the step size. The step size is optional and assumed to be 1 if we do not specify it.
If we want to run the code a certain number of times, we can use the ```range(start, stop, step)``` function, where ```start``` specifies the number we want to start from, ```stop``` the final number (excluding this value) and ```step``` the step size. The step size is optional and assumed to be 1 if we do not specify it.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
foriinrange(0,5,1):
foriinrange(0,5,1):
print('The value of i is now {}'.format(i))
print('The value of i is now {}'.format(i))
```
```
%% Output
%% Output
The value of i is now 0
The value of i is now 0
The value of i is now 1
The value of i is now 1
The value of i is now 2
The value of i is now 2
The value of i is now 3
The value of i is now 3
The value of i is now 4
The value of i is now 4
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
# We can iterate over a string as well:
# We can iterate over a string as well:
my_string='I love python'
my_string='I love python'
foriinmy_string:
foriinmy_string:
print(i)
print(i)
```
```
%% Output
%% Output
I
I
l
l
o
o
v
v
e
e
p
p
y
y
t
t
h
h
o
o
n
n
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
In some cases we may need to end the execution of the ```for``` loop early. There are two ways to do this:
In some cases we may need to end the execution of the ```for``` loop early. There are two ways to do this:
*```break```: this exists the loop and returns to the code outside the loop
*```break```: this exists the loop and returns to the code outside the loop
*```continue```: do not execute the rest of the current iteration in the loop but start with the next iteration
*```continue```: do not execute the rest of the current iteration in the loop but start with the next iteration
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
# Note here that we go through all values in the loop (0,1,2,3,4) but only print if the value is not equal to 2
# Note here that we go through all values in the loop (0,1,2,3,4) but only print if the value is not equal to 2
foriinrange(0,5,1):
foriinrange(0,5,1):
ifi==2:
ifi==2:
continue
continue
print('The value of i is now {}'.format(i))
print('The value of i is now {}'.format(i))
```
```
%% Output
%% Output
The value of i is now 0
The value of i is now 0
The value of i is now 1
The value of i is now 1
The value of i is now 3
The value of i is now 3
The value of i is now 4
The value of i is now 4
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
# Note here we abort the loop when we reach the value 2
# Note here we abort the loop when we reach the value 2
foriinrange(0,5,1):
foriinrange(0,5,1):
ifi==2:
ifi==2:
break
break
print('The value of i is now {}'.format(i))
print('The value of i is now {}'.format(i))
```
```
%% Output
%% Output
The value of i is now 0
The value of i is now 0
The value of i is now 1
The value of i is now 1
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
### Exercise: Fibonacci Series
### Exercise: Fibonacci Series
The [Fibonacci Numbers](https://en.wikipedia.org/wiki/Fibonacci_number) are a sequence where the current number is derived from the sum of the two preceeding ones, i.e. $F_n = F_{n-1} + F_{n-2}$. The first two numbers are $F_1 = 0$ and $F_2 = 1$. Therefore, the next number is $F_3 = 0 + 1 = 1$
The [Fibonacci Numbers](https://en.wikipedia.org/wiki/Fibonacci_number) are a sequence where the current number is derived from the sum of the two preceeding ones, i.e. $F_n = F_{n-1} + F_{n-2}$. The first two numbers are $F_1 = 0$ and $F_2 = 1$. Therefore, the next number is $F_3 = 0 + 1 = 1$
Write a ```for``` loop to compute the first 10 digits of the Fibonacci series and then print the series.
Write a ```for``` loop to compute the first 10 digits of the Fibonacci series and then print the series.
The for loop is pre-defined in the sense that the number of times the loop is executed is defined beforehand. If we loop, for example, over a dictionary or a list, we can access the individual elements and work with them.
The for loop is pre-defined in the sense that the number of times the loop is executed is defined beforehand. If we loop, for example, over a dictionary or a list, we can access the individual elements and work with them.
However, in many other cases we want to continue the execution until a suitable condition is met. In these cases, we use a ```while``` loop.
However, in many other cases we want to continue the execution until a suitable condition is met. In these cases, we use a ```while``` loop.
The general syntax is:
The general syntax is:
```
```
while <Statement is true>:
while <Statement is true>:
do something
do something
else:
else:
do something else
do something else
```
```
As with the ```for``` loop or the ```if``` statement, the ```else``` clause is optional.
As with the ```for``` loop or the ```if``` statement, the ```else``` clause is optional.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
i=0
i=0
whilei<=10:
whilei<=10:
print('The value of i is now {}'.format(i))
print('The value of i is now {}'.format(i))
i=i+1
i=i+1
```
```
%% Output
%% Output
The value of i is now 0
The value of i is now 0
The value of i is now 1
The value of i is now 1
The value of i is now 2
The value of i is now 2
The value of i is now 3
The value of i is now 3
The value of i is now 4
The value of i is now 4
The value of i is now 5
The value of i is now 5
The value of i is now 6
The value of i is now 6
The value of i is now 7
The value of i is now 7
The value of i is now 8
The value of i is now 8
The value of i is now 9
The value of i is now 9
The value of i is now 10
The value of i is now 10
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
Again, we can terminate the execution of the loop early with ```break``` and ```continue```.
Again, we can terminate the execution of the loop early with ```break``` and ```continue```.
***Note***
***Note***
It is quite important to think what will happen to the loop if we do use these statements.
It is quite important to think what will happen to the loop if we do use these statements.
For example, in the code below we first increase i, then do the check and then print the value, whereas above we first printed the value and then increased it by 1. We observe that, indeed, the value 2 is not printed, but the loop now runs between 1,...,11 instead of 0,...,10. However, if we were to place the statements in other orders, we would find that either there is not effect (the execution skips over everything after ```continue```) or we have an infinite loop, ...
For example, in the code below we first increase i, then do the check and then print the value, whereas above we first printed the value and then increased it by 1. We observe that, indeed, the value 2 is not printed, but the loop now runs between 1,...,11 instead of 0,...,10. However, if we were to place the statements in other orders, we would find that either there is not effect (the execution skips over everything after ```continue```) or we have an infinite loop, ...
Using these statements can be quite tricky and you may introduce subtle bugs or unwanted behaviour with them...
Using these statements can be quite tricky and you may introduce subtle bugs or unwanted behaviour with them...
***Exercise***
***Exercise***
Try and see what the effect is of using a different order of statements inside the loop.
Try and see what the effect is of using a different order of statements inside the loop.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
i=0
i=0
whilei<=10:
whilei<=10:
i=i+1
i=i+1
ifi==2:
ifi==2:
continue
continue
print('The value of i is now {}'.format(i))
print('The value of i is now {}'.format(i))
```
```
%% Output
%% Output
The value of i is now 1
The value of i is now 1
The value of i is now 3
The value of i is now 3
The value of i is now 4
The value of i is now 4
The value of i is now 5
The value of i is now 5
The value of i is now 6
The value of i is now 6
The value of i is now 7
The value of i is now 7
The value of i is now 8
The value of i is now 8
The value of i is now 9
The value of i is now 9
The value of i is now 10
The value of i is now 10
The value of i is now 11
The value of i is now 11
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
i=0
i=0
whilei<=10:
whilei<=10:
print('The value of i is now {}'.format(i))
print('The value of i is now {}'.format(i))
i=i+1
i=i+1
ifi==2:
ifi==2:
break
break
```
```
%% Output
%% Output
The value of i is now 0
The value of i is now 0
The value of i is now 1
The value of i is now 1
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
### Exercise
### Exercise
Rewrite the Fibonacci Series as a ```while``` loop, terminating after the list is 10 elements long.
Rewrite the Fibonacci Series as a ```while``` loop, terminating after the list is 10 elements long.
(Alternatively, until the series arrives at the value of 34.)
(Alternatively, until the series arrives at the value of 34.)