Python 3.14 ·
✓ verified by execution on 2026-07-21
So far your programs have run every line, top to bottom, no matter what. The if statement is how you give a program a choice: run this block only when a condition is true. It’s the single most common way to make code react to its input.
python
x = 5if x > 0: print('Positive')
Output
Positive
Your output
Adding an else branch
python
x = -2if x > 0: print('Positive')else: print('Non-positive')
Output
Non-positive
Your output
Chaining with elif
When you have more than two cases, chain them with elif (short for “else if”). Python checks each condition in order and runs the first block whose condition is true — then skips the rest. Both elif and else are optional.
python
x = 0if x > 0: print('Positive')elif x == 0: print('Zero')else: print('Negative')
is_raining = Trueif is_raining: print('Take an umbrella')print('Go outside')
Output
Take an umbrella
Go outside
Your output
Nested Conditionals
python
x = 10y = 5if x > 5: if y > 2: print('Both conditions met') else: print('Only first condition met')else: print('First condition not met')
Output
Both conditions met
Your output
Common Misconceptions
Myth: Python uses braces {} to define code blocks like C or Java.
Reality: Python uses indentation (whitespace) to mark what’s inside a block. Line up your code consistently — four spaces is the convention.
Myth: Every elif whose condition is true will run.
Reality: An if/elif chain stops at the first true condition, runs that one block, and skips all the rest.
Myth: The colon : at the end of an if line is optional.
Reality: The colon is required — it marks the start of the indented block. Leaving it off raises a SyntaxError.
Under the Hood
Watch how execution jumps directly past unmatched branches: