Skip to content
Snippets Groups Projects
Commit c7cbbf75 authored by Ulrich Kerzel's avatar Ulrich Kerzel
Browse files

indent

parent 5d287eba
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
# Flow Control
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.
Therefore, we now look at elements how to control the flow of our programs:
* ```if``` statements
* ```for``` loops
* ``` while``` loops
* iterating over lists or dictionaries, etc.
## Checking for conditions
### If statement
The ``if`` statement is the simplest way to conditionally execute some code (or not).
The general syntax is:
```
if condition:
action
```
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```:
* Equal: ```a == b```.
Note the double ``` ==``` : a single ```=``` is used for assignments, so we need to use the double ```==``` for a comparison
* not equal: ``` a != b```
* less than: ```a < b``` or less equal ``` a <= b ```
* greater than: ``` a > b``` or greater equal ``` a >= b```
%% Cell type:code id: tags:
``` python
a = 1
b = 2
# First we can look what the condition might be:
print (a > b)
# now do a conditional:
if a > b:
print('a is greater than b')
print('--------')
```
%% Output
False
--------
%% Cell type:markdown id: tags:
... 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.
> **Note**
>
> 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...
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:
``` python
a = 10
if a > 100:
print ('a is greater than 100')
elif a > 50:
print ('a is greater than 50')
elif a > 10:
print ('a is greater than 10')
else:
print ('none applies')
```
%% Output
none applies
%% Cell type:code id: tags:
``` python
# if we only have one condition to test, we can write a short one-liner
a = 1
b = 2
print ('a is greater than b') if a > b else print ('b is greater than a')
```
%% Output
b greater than a
%% Cell type:markdown id: tags:
We can also have more than one condition and combine them using ```and``` , ```or```.
%% Cell type:code id: tags:
``` python
a = 10
b = 15
if (a > 10) and (b < 20):
print('condition met')
```
%% Cell type:markdown id: tags:
We can also nest ```if``` statements, i.e. have ```if``` statements within ```if``` statements.
**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.
%% Cell type:code id: tags:
``` python
a = 27
# ... your code here ...
```
%% Cell type:markdown id: tags:
---
## 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.
In this case, we can use the ```for``` loop.
The general syntax is
```
for variable in list:
do something
else:
else:
do something else
```
(where typically we do not need the ```else``` statement.)
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.
%% Cell type:code id: tags:
``` python
for i in range(0, 5, 1):
print('The value of i is now {}'.format(i))
```
%% Output
The value of i is now 0
The value of i is now 1
The value of i is now 2
The value of i is now 3
The value of i is now 4
%% Cell type:code id: tags:
``` python
# We can iterate over a string as well:
my_string = 'I love python'
for i in my_string:
print(i)
```
%% Output
I
l
o
v
e
p
y
t
h
o
n
%% 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:
* ```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
%% Cell type:code id: tags:
``` 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
for i in range(0, 5, 1):
if i == 2:
continue
print('The value of i is now {}'.format(i))
```
%% Output
The value of i is now 0
The value of i is now 1
The value of i is now 3
The value of i is now 4
%% Cell type:code id: tags:
``` python
# Note here we abort the loop when we reach the value 2
for i in range(0, 5, 1):
if i == 2:
break
print('The value of i is now {}'.format(i))
```
%% Output
The value of i is now 0
The value of i is now 1
%% Cell type:markdown id: tags:
### 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$
Write a ```for``` loop to compute the first 10 digits of the Fibonacci series and then print the series.
The output should be:
```
The Fibonacci numbers are: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
```
%% Cell type:code id: tags:
``` python
# ... your code here ....
```
%% Cell type:markdown id: tags:
## While Loops
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.
The general syntax is:
```
while <Statement is true>:
do something
else:
do something else
```
As with the ```for``` loop or the ```if``` statement, the ```else``` clause is optional.
%% Cell type:code id: tags:
``` python
i = 0
while i <= 10:
print('The value of i is now {}'.format(i))
i = i +1
```
%% Output
The value of i is now 0
The value of i is now 1
The value of i is now 2
The value of i is now 3
The value of i is now 4
The value of i is now 5
The value of i is now 6
The value of i is now 7
The value of i is now 8
The value of i is now 9
The value of i is now 10
%% Cell type:markdown id: tags:
Again, we can terminate the execution of the loop early with ```break``` and ```continue```.
***Note***
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, ...
Using these statements can be quite tricky and you may introduce subtle bugs or unwanted behaviour with them...
***Exercise***
Try and see what the effect is of using a different order of statements inside the loop.
%% Cell type:code id: tags:
``` python
i = 0
while i <= 10:
i = i +1
if i == 2:
continue
print('The value of i is now {}'.format(i))
```
%% Output
The value of i is now 1
The value of i is now 3
The value of i is now 4
The value of i is now 5
The value of i is now 6
The value of i is now 7
The value of i is now 8
The value of i is now 9
The value of i is now 10
The value of i is now 11
%% Cell type:code id: tags:
``` python
i = 0
while i <= 10:
print('The value of i is now {}'.format(i))
i = i +1
if i == 2:
break
```
%% Output
The value of i is now 0
The value of i is now 1
%% Cell type:markdown id: tags:
### Exercise
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.)
%% Cell type:code id: tags:
``` python
# ... your code here ...
```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment