Python if-else Statement
In this page:
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")
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")
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"
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:
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:
print("Entry allowed")
else:
print("Entry denied")
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: