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 (PHP) and not else if as two words. This is one of the most common typos coming from another language.
Python has no direct equivalent to PHP's switch (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 write what PHP's stacked case labels do.
A compact one-line if/else, with the condition in the middle rather than PHP's ?/::
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