Python if-else Statement
In this page:
if condition:
# code if True
else:
# code if False
Standard If-Else
An if/else statement picks exactly one of two code paths: the if block runs when the condition is True, and the else block runs automatically whenever it's False — every input hits one branch or the other, never both.
Example: Standard If-Else
age = 15
if age >= 18:
print("Adult")
else:
print("Minor") # runs because age >= 18 is False
Boolean Flag Checks
Pairing if/else with a boolean flag variable creates a clean toggle or gate — for example, if is_logged_in: versus else: — that reads naturally and keeps program state checks easy to follow at a glance.
Example: Boolean Flag Checks
is_logged_in = False
if is_logged_in:
print("Welcome back")
else:
print("Please log in") # runs because the flag is False
Variable Assignment with If-Else
Assigning a variable's value based on a condition, like status = "adult" if age >= 18 else "minor", is a common pattern for deriving one value from another without a multi-line block cluttering the surrounding logic.
Example: Variable Assignment with If-Else
age = 16
status = "adult" if age >= 18 else "minor" # derive status from age in one line
print(status)
Logic with Strings
The in keyword checks membership directly inside a condition — if "@" in email: — letting you test whether a substring, character, or item appears in a string, list, or other collection without a separate search step.
Example: Logic with Strings
email = "[email protected]"
if "@" in email: # membership check for a substring
print("Looks like a valid email")
else:
print("Missing @ symbol")
Combining Logical Operators
Combining multiple checks with and/or inside a single if/else condition — like if age >= 18 and has_id: — lets you gate a branch on several criteria at once instead of nesting several separate if statements.
Example: Combining Logical Operators
age = 20
has_id = True
if age >= 18 and has_id: # both conditions must be True
print("Entry allowed")
else:
print("Entry denied")
- Placing
elseat a different indentation than itsif, which raisesIndentationErroror attaches it to the wrong statement. - Writing
else x > 5:with a condition;elsenever takes a condition (useelif). - Using two separate
ifstatements where oneif/elsewas meant, so both blocks can run.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: