As we develop more complex code, it is quite common to want to have your code do different things depending on the value. For instance, suppose you are recoding heartrates, and the numerical values should be “low” if it is between 0 and 60, “medium” if it is between 60 and 100, “high” if it is above 100, and “unknown” otherwise (when it is below 0 or other data type).
Stepping back, we have been working with a linear way of executing code - we have unconditionally executing every line of code in our program. Here, we are create a “control flow” via conditional statements in which the your code will run a certain section if some conditions are met.
Here is how the syntax looks like for conditional statements:
if <expression1>:
block of code 1
elif <expression2>:
block of code 2
else:
block of code 3
block of code 4
There are three possible ways the code can run:
If <expression1> is evaluated as True, then block of code 1 will be run. When done, it will continue to block of code 4.
If <expression1> is evaluated as False, then it will ask if <expression2> is True or not. If True, then block of code 2 will be run. When done, it will continue to block of code 4.
If <expression1> and <expression2> are both evaluated as False, then block of code 3 is run. When done, it will continue to block of code 4.
An important takeaway is that only one block of code can be run.
Let’s see how this apply to the data recoding example. Let’s just assume the data we want to recode is just a single value in a variable rate, not the entire list heartrates:
You don’t always need multiple if, elif, else statements when writing conditional statements. In its simplest form, a conditional statement requires only an if clause:
x =-12if x <0: x = x *-1print(x)
12
Then, you can add an elif or else statement, if you like. Here’s if-elif:
x =.25if x <0: x = x *-1elif x >=0and x <1: x =1/ xprint(x)
4.0
Here’s if-else. The in statement asks whether an element (102) is found in an iterable data structure heartrates, and returns True if so:
if102in heartrates:print("Found 102.")else:print("Did not find 102.")
Found 102.
Finally, let’s put the data recoding example within a For-Loop: