Conditionals let a script make decisions — the same idea from Intro to Programming, with Python's indentation-based syntax and no parentheses required around the condition.
score = 72
if score >= 90:
print("Grade: A")
elif score >= 75:
print("Grade: B")
elif score >= 60:
print("Grade: C")
else:
print("Grade: F")Python spells the middle case elif — not elseif and not else if as two words. This is one of the most common typos when you're getting used to Python's syntax.
Python has no switch statement the way many other languages do (a genuine match statement was added in Python 3.10, but a long elif chain remains the more common, portable way to write this):
day = "Mon"
if day in ("Mon", "Tue", "Wed", "Thu", "Fri"):
print("Weekday")
elif day in ("Sat", "Sun"):
print("Weekend")
else:
print("Not a valid day")in (...) — checking whether a value is one of several — is the idiomatic Python way to check a value against a list of options.
A compact one-line if/else, with the condition placed in the middle:
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # "adult"Because of Python's truthy/falsy rules (from the Type Conversion lesson), checking whether a list or string is empty rarely needs a length check:
items = []
if items:
print("Has items")
else:
print("Empty") # this runs — an empty list is falsy:= — nicknamed the walrus operator for its resemblance to a pair of eyes and tusks — assigns a value and returns it in the same expression, added in Python 3.8. Its most common use is avoiding calling the same thing twice:
# Without the walrus — calling len() twice:
names = ["Priya", "Amit", "Sara"]
if len(names) > 2:
print(f"{len(names)} names")
# With the walrus — computed once, used twice:
if (count := len(names)) > 2:
print(f"{count} names")It's a small convenience, not a feature you'll need constantly — reach for it when the same value would otherwise be computed twice in an if condition and its body.