There are many times in life where what we would like to do next depends on some aspect of what’s currently happening at this moment.

For example, when you wake up in the morning you may decide to wear a sweatshirt if it’s cold outside or just a t-shirt if it’s not. Likewise for during the day, if you perfectly understand the day’s lecture you will spend the afternoon with friends. If you understood most of it, then you will go to the library for a bit before meeting your friends for dinner. If you were totally lost, then you’ll just go to the library for the rest of the day! (no Monday Night football 😢)

Python provides a way to express the same structure via conditionals. If we’ll wear a sweatshirt if it’s cold outside, but otherwise a t-shirt, we can express this via an if/else

if temperature == 'cold':
	print("I will wear a sweatshirt")
else:
	print("I will wear a t-shirt")

In the above code block, Python first evaluates the condition that follows the if keyword: temperature == 'cold' . Temperature must have been previously defined or else Python will throw an error. So assuming that it has been defined, Python will evaluate this expression as either True or False. If True, Python will run the indented code block beneath the condition. In our example, we’d see “I will wear a sweatshirt” printed to the screen. If False, though, Python will skip the code block beneath the if condition. It won’t run it. Instead it will jump to the indented code block beneath else and run that.

As our second example about the extent to which we understood the day’s class highlights though, the condition of interest might not be binary. We can express this in python by introducing as many elif statements as we might need to capture the additional conditions. For example:

if (temperature < 40) and (temperature > 30):
	print("I will wear a sweatshirt")
elif temperature <= 30:
	print("I will wear a winter coat")
elif (temperature >=40) and (temperature <60):
	print("I will wear a long sleeve shirt")
else:
	print("I will wear a t-shirt")