Selection
We previously focussed on the components that form simple statements, which is the first building block that we introduced in our pre-sessional videos.
We will now look at what is known as compound statements.
The first of these is our second building block – the selection block.
We have seen if
statements.
if user_guess == 42:
print("Correct")
And the two-way if-else
statements.
if user_guess == 42:
print("Correct")
else:
print("Incorrect")
We have also looked at how you can nest a selection block inside another selection block.
if user_guess == 42:
print("Correct")
else:
if user_guess < 42:
print("Too low")
else:
print("Too high")
But this might get a bit too messy and hard to read if you overdo it.
if user_guess == 42:
print("Correct")
else:
if user_guess == 41:
print("Very very very close")
else:
if user_guess == 40:
print("Very very close")
else:
if user_guess == 39:
print("Very close")
else:
if user_guess == 38:
print("Close")
else:
if user_guess == 37:
print("Close-ish")
else:
...
Python offers a more elegant solution for this: a multi-way selection statement.
if user_guess == 42:
print("Correct")
elif user_guess == 41:
print("Very very very close")
elif user_guess == 40:
print("Very very close")
else:
print("Incorrect")
elif
means “else if”. It’s just shorter (aligns better with else
)!
Also remember that if
accepts any boolean expressions as a condition. So you can use operators like or
or and
to combine multiple conditions.
if user_guess > 42 and user_guess < 35:
print("Hot")
You can even do this.
if True:
print("I am always true.")
else:
print("I don't think anyone will ever see me.")
But you have better have a good reason to do this!