Skip to content
IT Vizag
← Decisions & Loops

if, elif and else

Lesson 2 of 9 · 1 min read

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.

Tip: Test every path. For the grade example, try 95, 80, 65, 40 and 10, plus the edge values like 90 and 35.

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.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend