Loading lessons...
If...Else Basics
If...Else Basics
Python uses if, elif, and else to make decisions.
if
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:
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:
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:
if a > b: print("a is greater than b")
Short hand if...else (ternary)
print("A") if a > b else print("B")
TL;DR
ifchecks a condition;elifchecks another;elsecatches the rest.- Indentation defines the block.
- One-liners exist for very short logic.