Lesson 55 +10 XP

If...Else Basics

Python uses if, elif, and else to make decisions.

if


python
a = 33
b = 200
if b > a:
    print("b is greater than a")

The indented block runs only when the condition is True.

elif

elif means "else if". It checks another condition when the first is false:


python
a = 33
b = 33
if b > a:
    print("b is greater than a")
elif a == b:
    print("a and b are equal")

else

else catches everything that didn't match:


python
a = 200
b = 33
if b > a:
    print("b is greater than a")
elif a == b:
    print("a and b are equal")
else:
    print("a is greater than b")

Short hand if

One statement on one line:


python
if a > b: print("a is greater than b")

Short hand if...else (ternary)


python
print("A") if a > b else print("B")

TL;DR

  • if checks a condition; elif checks another; else catches the rest.
  • Indentation defines the block.
  • One-liners exist for very short logic.