Python If...Else
Make decisions — run different code depending on conditions.
Basic syntax
Python
age = 18
if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")
Indentation is the syntax
Python uses indentation (4 spaces by convention) to define code blocks, not curly braces. Every line inside the if/elif/else must be indented exactly the same amount.
Comparison and logical operators
Python
x, y = 10, 20
if x > 0 and y > 0: # both conditions true
print("Both positive")
if x == 10 or y == 10: # at least one true
print("At least one is 10")
if not x == 0: # negation
print("x is not zero")
Ternary expression (one-liner if-else)
Python
age = 20
status = "adult" if age >= 18 else "minor"
score = 75
grade = "A" if score >= 90 else "B" if score >= 80 else "C"
Checking for None, empty, membership
Python
value = None
if value is None: # ✅ correct way to check None
print("No value")
items = []
if not items: # empty list is falsy
print("List is empty")
name = "Raman"
if "R" in name: # membership test
print("Starts with R")
match-case (Python 3.10+)
Python 3.10+
command = "quit"
match command:
case "quit":
print("Quitting")
case "help":
print("Showing help")
case _: # default
print("Unknown command")