← Back to Python Course | Chapter 3: Control Flow | Lesson 2 of 10

Python if-else Statement

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

python
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

python
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

python
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

python
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

python
age = 20
has_id = True
if age >= 18 and has_id:
    print("Entry allowed")
else:
    print("Entry denied")

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.