Conditional Statements
Updated on 28 Dec 2022
These are branching mechanisms whereby you choose to do something if a certain condition is met.
if
At it’s most basic, the if
conditional can be used to determine if a block of code should be executed. Consider a case where we want to see if the temperature
is higher than 35.
temperature_high = 35
temperature = 37
if temperature > temperature_high:
print('It is really hot today')
Info: You can inverse a conditional with the not qualifier immediately after if
grouping
We can also group multiple conditions together. In this case we want a temperature between 25 and 35 for a ‘comfortable range’.
temperature_low = 25
temperature_high = 35
temperature = 28
if temperature > temperature_low and temperature < temperature_high:
print('At {0}, it is comfortable today'.format(str(temperature)))
else
So far we’ve seen examples where the condition is met. The else
keyword is used where the condition is not met.
temperature_high = 35
temperature = 28
if temperature > temperature_high:
print('You will probably melt today')
else:
print('You will NOT be melting today')
elif
We can use elif
keyword where we need a larger type of response range.
temperature = 28
if temperature > 35:
print('You will probably melt today')
elif temperature > 20 and temperature <= 35:
print('You should hold your form today')
else:
print('You might feel cold today')