Back to course

Conditional Statements 2: `if`, `else`, and Mutual Exclusion

Python Programming: The 0 to Hero Bootcamp

The if...else Statement

Often, if a condition is not met, you want to execute an alternative block of code. This creates a mutually exclusive path: one block will run, and the other will not.

Syntax

python if condition: # Runs if condition is True block_A else: # Runs if condition is False block_B

Example: Pass/Fail Grading

python score = 75 passing_grade = 80

if score >= passing_grade: print("Congratulations! You passed.") status = 'Pass' else: print("Better luck next time. Study harder.") status = 'Fail'

print(f"Final status: {status}")

Shorthand If (Ternary Operator)

For very simple if/else assignments, Python offers a concise one-line syntax (the Ternary Conditional Operator):

python

Syntax: value_if_true if condition else value_if_false

age = 15 drink = "Coke" if age >= 18 else "Milk" print(f"The user will be served: {drink}")