What if we want to check through several boolean statements? We could use a nested if-else block:
if statement:
code
else:
if statement 2:
code
else:
code
The better way is with an elif statement, short for else if. Here's the format:
if statement:
code # This code is run if statement is True.
elif statement 2:
code # This code is run if statement is False and statement 2 is True.
else:
code # This code is run if neither statement is True!
You can have as many elifs as you want. You don't even need an else statement! Python will go through each statement until it finds one that is True. Then it stops the if statement and runs the code inside.
Improving on our already improved example, let's add an elif or two.
num = int(float(input("Enter a number:")))
if num < 10:
print("Your number is less than 10.")
elif num < 20:
print("Your number is less than 20.")
elif num < 30:
print("Your number is less than 30.")
else:
print("Your number is not less than 10, 20, or 30.")