2.1. Conditions and if
statements#
In previous Sections you have learned how to create variables, alter them with the help of operators and access the code of professional software developers/scientists. With this, you can already do plenty of stuff in Python. However, it still lacks versatility. If you want to apply other processing techniques for other data — you would need to manually rewrite your code and then change it back once the data changes again. Not that handy, right?
In this Section you will learn how to steer the flow of your code — process data differently based on some conditions. For that you will learn a construction called the if
statement.
2.1.1. if
keyword#
The if
statement in Python is similar to how we use it in English. ”If I have apples, I can make an apple pie” — clearly states that an apple pie will exist under the condition of you having apples. Otherwise, no pie.
Well, it is the same in Python:
amount_of_apples = 0
if amount_of_apples > 0:
print("You have apples!\nLet's make a pie!")
print('End of the cell block...')
End of the cell block...
As you can see - nothing is printed besides ’End of the cell block…’.
But we can clearly see that there is another print statement! Why it is not printed? Because we have no apples… thus no pie for you.
Let’s acquire some fruit and see whether something will change…
Adding 5 apples to our supply:
amount_of_apples += 5
if amount_of_apples > 0:
print("You have apples!\nLet's make a pie!")
print('End of the cell block...')
You have apples!
Let's make a pie!
End of the cell block...
Now you can see that the same if
statement prints text. It happened because our statement amount_of_apples > 0
is now True
.
That’s how an if
statement works — you type the if
keyword, a statement and a colon. Beneath it, with an indentation of 4 spaces (1 tab), you place any code you want to run in case that if
statement is True
. This indentation is the same as described in Notebook 1 when defining a function.
If the result of the conditional expression is False
, then the code inside of the if
statement block will not run. Here’s another example:
my_age = 25
if my_age >= 18 and my_age <= 65:
print("I'm an adult, I have to work right now :(")
print('End of the cell block...')
I'm an adult, I have to work right now :(
End of the cell block...
Slightly different setting but still the same construction. As you can see in this case, the condition of the if
statement is more complicated than the previous one. It combines two smaller conditions by using the keyword and
. Only if both conditions are True
the final result is True
(otherwise it would be False
).Thus, the condition can be as long and as complicated as you want it to be, just make sure that it is readable.
elif
keyword
Now, let's add a bit more logic to our last example:
my_age = 25
if my_age >= 18 and my_age <= 65:
print("I'm an adult, I have to work right now :(")
elif my_age > 65:
print("I can finally retire!")
print('End of the cell block...')
I'm an adult, I have to work right now :(
End of the cell block...
Still the same output, but what if we change our age…
my_age = 66
if my_age >= 18 and my_age <= 65:
print("I'm an adult, I have to work right now :(") # msg #1
elif my_age > 65:
print("I can finally retire!") # msg #2
print('End of the cell block...')
I can finally retire!
End of the cell block...
See.. we have a different output. Changing the value of our variable my_age
changed the output of the if
statement. Furthermore, the elif
keyword helped us to add more logic to our code. Now, we have three different output scenarios:
print message #\(1\) if
my_age
is within the \([18, 65]\) range;print message #\(2\) if
my_age
is bigger than \(65\); and,print none of them if
my_age
doesn’t comply with none of the conditions (as shown below).
my_age = 15
if my_age >= 18 and my_age <= 65:
print("I'm an adult, I have to work right now :(") # msg #1
elif my_age > 65:
print("I can finally retire!") # msg #2
print('End of the cell block...')
End of the cell block...
One can also substitute an elif
block by a different if
block, however it is preferred to use elif
instead to ”keep the condition together” and to reduce code size.
Warning
It is important to know that there should be only one if
block and any number of elif
blocks within it.
A last example below setting my_age = 88
to run the first elif
block and setting my_age = 7
to run the second elif
block.
my_age = 88
if my_age >= 18 and my_age <= 65:
print("I'm an adult, I have to work right now :(")
elif my_age > 65:
print("I can finally retire!")
elif my_age < 10:
print("I'm really, really young")
my_age = 7
if my_age >= 18 and my_age <= 65:
print("I'm an adult, I have to work right now :(")
elif my_age > 65:
print("I can finally retire!")
elif my_age < 10:
print("I'm really really young")
print('End of the cell block...')
I can finally retire!
I'm really really young
End of the cell block...
2.1.2. else
keyword#
We can go even further and add an additional scenario to our if
statement with the else
keyword. It runs the code inside of it only when none of the if
and elif
conditions are True
:
my_age = 13
if my_age >= 18 and my_age <= 65:
print("I'm an adult, I have to work right now :(")
elif my_age > 65:
print("I can finally retire!")
elif my_age < 10:
print("I'm really really young")
else:
print("I'm just young")
print('End of the cell block...')
I'm just young
End of the cell block...
On the previous example, since my_age
is not between \([18,65]\), nor bigger than \(65\), nor smaller than \(10\), the else
block is run.
Below, a final example setting my_age = 27
to run the if
block, then setting my_age = 71
to run the first elif
block. To run the second elif
block we set my_age = 9
. Finally, setting my_age = 13
to run the else
block.
my_age = 27
if my_age >= 18 and my_age <= 65:
print("I'm an adult, I have to work right now :(")
elif my_age > 65:
print("I can finally retire!")
elif my_age < 10:
print("I'm really really young")
else:
print("I'm just young")
print('End of the cell block...')
print('------------------------')
my_age = 71
if my_age >= 18 and my_age <= 65:
print("I'm an adult, I have to work right now :(")
elif my_age > 65: # first elif block
print("I can finally retire!")
elif my_age < 10:
print("I'm really really young")
else:
print("I'm just young")
print('End of the cell block...')
print('------------------------')
my_age = 9
if my_age >= 18 and my_age <= 65:
print("I'm an adult, I have to work right now :(")
elif my_age > 65:
print("I can finally retire!")
elif my_age < 10: # second elif block
print("I'm really really young")
else:
print("I'm just young")
print('End of the cell block...')
print('------------------------')
my_age = 13
if my_age >= 18 and my_age <= 65:
print("I'm an adult, I have to work right now :(")
elif my_age > 65:
print("I can finally retire!")
elif my_age < 10:
print("I'm really really young")
else: # else block
print("I'm just young")
print('End of the cell block...')
print('------------------------')
I'm an adult, I have to work right now :(
End of the cell block...
------------------------
I can finally retire!
End of the cell block...
------------------------
I'm really really young
End of the cell block...
------------------------
I'm just young
End of the cell block...
------------------------
That’s almost everything you have to know about if
statements! The last two things are:
It goes from top to bottom. When the first condition to be
True
runs, it skips all conditions after it — as shown below:
random_number = 17
if random_number > 35:
print('Condition #1')
elif random_number > 25:
print('Condition #2')
elif random_number > 15:
print('Condition #3')
elif random_number > 5:
print('Condition #4')
else:
print('Condition #5')
Condition #3
You can put almost everything inside each condition block and you can define variables within each block:
my_income = 150
my_degree = 'BSc'
if my_degree == 'BSc':
x = 5
if my_income > 300:
b = 2
print('I am a rich BSc student')
else:
print('I am a poor BSc student')
elif my_degree == 'MSc':
if my_income > 300:
print('I am a rich MSc student')
else:
print('I am a poor MSc student')
print('x =', x)
print('b =', b)
I am a poor BSc student
x = 5
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[22], line 20
17 print('I am a poor MSc student')
19 print('x =', x)
---> 20 print('b =', b)
NameError: name 'b' is not defined
As you can see, we can make it as complicated as we want in terms of conditional branching.
Additionally, you can see that only variables within the blocks which run were created, while other variables were not. Thus, we have a NameError that we tried to access a variable (b)
that was not defined.