if, elif and else
Make your program take different paths.
🎬 Video version coming soon — read it now
An if statement runs a block of code only when a condition is True.
temperature = 36
if temperature > 35:
print("It's hot. Carry water!")
print("Have a good day")Indentation matters
The lines that belong to the if are indented by 4 spaces. That's how Python knows where the block starts and ends. Colab adds the spaces automatically after you type the colon : and press Enter.
Forget the colon or the indent and you'll get a SyntaxError or an IndentationError.
else: the other path
age = int(input("Your age: "))
if age >= 18:
print("You can vote.")
else:
print(f"You can vote in {18 - age} years.")Exactly one of the two blocks runs, never both.
elif: more than two choices
marks = int(input("Marks out of 100: "))
if marks >= 90:
grade = "A+"
elif marks >= 75:
grade = "A"
elif marks >= 60:
grade = "B"
elif marks >= 35:
grade = "C"
else:
grade = "Fail"
print(f"Grade: {grade}")Python checks the conditions top to bottom and runs the first one that is True, then skips the rest. That's why the order matters: if you checked marks >= 35 first, 95 marks would get a C.
Nested if
You can put an if inside another if, but keep it shallow. More than two levels deep usually means the code can be written more simply.
In one line
if runs code when a condition is True, elif adds more choices, else catches everything left, and the indentation marks each block.
Share with a friend