These are the notes for Python episode 6. Until now, every program ran straight down, every line, every time. Today the program learns to choose. You will learn the if statement, why Python insists on a colon and on indentation, else for the other road, elif chains (and why their order matters), checking for empty input with if name:, nested if, the one-line if/else, and the real error messages you will meet on the way. Every example below runs as-is in the SyntaxPilot compiler (type the input in the input box before you press Run), with its real output from Python 3.13.
The problem: a discount for everyone
In episode 4, Raju made an offer: more than 10 cups gets 10% off. So we add one line to the bill program that takes 10% off:
cups = int(input("Cups: "))
bill = cups * 12
bill = bill - bill * 10 / 100
print("Pay:", bill)
Input 2 → output Cups: Pay: 21.6
(In the SyntaxPilot compiler the typed input isn't echoed, so the prompt and the output appear on one line.)
A student buys 2 cups and pays ₹21.6 instead of ₹24. The discount ran for a 2-cup order.
Why it failed: every program so far runs straight down, top to bottom, every line, every time. It can even work out
cups > 10and getTrueorFalse, but it can't use that answer to skip a line. Straight-line code can't choose.
if: the fork in the road
Imagine a highway with a signboard: "Trucks only: take the side road".
| On the road | In Python |
|---|---|
| The signboard asks a question: "Truck?" | if cups > 10: asks a True/False question |
| Only matching vehicles take the side road | the indented line(s) below run only when the answer is True |
| Everyone meets again on the main road | the next line back at the left edge runs for everyone |
A condition is any question whose answer is True or False, like cups > 10. The if statement runs a piece of code only when its condition is True.
Mistake 1: forgetting the colon
cups = int(input("Cups: "))
bill = cups * 12
if cups > 10
bill = bill * 0.9
print("Pay:", bill)
File "main.py", line 3
if cups > 10
^
SyntaxError: expected ':'
A SyntaxError means Python couldn't even read your code: it breaks the grammar rules of the language, so nothing runs. The colon (:) at the end of the if line tells Python "the question has ended, the side road starts now".
Mistake 2: forgetting the indentation
cups = int(input("Cups: "))
bill = cups * 12
if cups > 10:
bill = bill * 0.9
print("Pay:", bill)
File "main.py", line 4
bill = bill * 0.9
^^^^
IndentationError: expected an indented block after 'if' statement on line 3
Python needs to know which lines belong to the side road. An IndentationError is a kind of SyntaxError about the spaces at the start of lines.
Colon + indentation = a block
if cups > 10:
bill = bill * 0.9 # inside if
print("10% off!") # inside if
print("Pay:", bill) # everyone
- The
ifline ends with a colon. - Indentation is the empty space at the start of a line. Every line that belongs to the
ifis pushed right by 4 spaces. - The indented lines together are called a block: a group of lines that run (or are skipped) together.
- The first line back at the left edge is outside the
if, and runs for everyone.
Other languages (Java, C, JavaScript) mark blocks with curly brackets { }. Python uses indentation, so in Python spaces are not decoration. Four spaces is the standard, and every line in one block must line up exactly.
The working if
cups = int(input("Cups: "))
bill = cups * 12
if cups > 10:
bill = bill * 0.9
print("10% off!")
print("Pay:", bill)
| Input | Output |
|---|---|
12 |
Cups: 10% off! then Pay: 129.6 |
2 |
Cups: Pay: 24 |
With 12 cups the side road ran. With 2 cups the indented block was skipped, and print("Pay:", bill) ran for both. (bill * 0.9 keeps 90% of the bill, which is the same as taking 10% off.)
Mistake 3: = instead of ==
cups = int(input("Cups: "))
if cups = 12:
print("A dozen!")
File "main.py", line 2
if cups = 12:
^^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
= stores a value; == compares two values. An if needs a question, so write if cups == 12:. Python even suggests the fix. (:= is the "walrus" operator, an advanced tool you can ignore for now.)
else: the other road
Raju wants small orders to get a message too. That's the other road, and it's called else:
cups = int(input("Cups: "))
bill = cups * 12
if cups > 10:
bill = bill * 0.9
print("10% off!")
else:
print("Buy", 11 - cups, "more for 10% off")
print("Pay:", bill)
| Input | Output |
|---|---|
8 |
Cups: Buy 3 more for 10% off then Pay: 96 |
12 |
Cups: 10% off! then Pay: 129.6 |
elsehas no condition. It simply means "everything theifdidn't catch".- It ends with a colon and has its own indented block.
- With
if/else, exactly one of the two roads runs: never both, never neither.
elif: more than two roads
Priya scored 95. Her school's grades: 90 and above is A, 75 and above is B, 50 and above is C. Three rules, so we write three ifs:
marks = int(input("Marks: "))
if marks >= 90:
print("Grade A")
if marks >= 75:
print("Grade B")
if marks >= 50:
print("Grade C")
Input 95 → Marks: Grade A, Grade B, Grade C (three lines). Her report card shows three grades! Three separate ifs are three separate questions. 95 is at least 90, at least 75 and at least 50, so all three are True and all three print.
We need: check these in order, and stop at the first one that's True. That's elif, short for "else if":
marks = int(input("Marks: "))
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
Input 95 → Marks: Grade A (only A).
Once one branch (one of the possible roads) is True, Python skips every elif and else below it.
Real-life example: station security lanes
| At the railway station | In Python |
|---|---|
| Check 1: "VIP pass?" If yes, VIP lane. No more questions. | if marks >= 90: is asked first |
| Check 2: "With family?" Asked only if you weren't VIP | elif marks >= 75: is asked only if everything above was False |
| Everyone else: general lane | else: catches the rest |
Order matters
Write the same chain the other way round:
marks = int(input("Marks: "))
if marks >= 50:
print("Grade C")
elif marks >= 75:
print("Grade B")
elif marks >= 90:
print("Grade A")
Input 95 → Marks: Grade C. Grade C for 95! 95 is at least 50, so the first branch wins and the A is never even checked. No error, just a wrong answer. Rule: put the strictest condition first.
else as the catch-all
Back to 90, 75, 50, and add two lines at the end of the elif program:
else:
print("Fail, try again")
| Input | Output |
|---|---|
95 |
Marks: Grade A |
80 |
Marks: Grade B |
60 |
Marks: Grade C |
40 |
Marks: Fail, try again |
A catch-all is a final branch that handles every case nobody else did. Now every possible mark gets exactly one result.
How the chain flows
marks >= 90 ? ── yes ──> "Grade A" ──┐
│ no │
marks >= 75 ? ── yes ──> "Grade B" ──┤
│ no │
marks >= 50 ? ── yes ──> "Grade C" ──┤
│ no │
else ──────────────> "Fail" ────┤
v
rest of the program
| Part | Has a condition? | How many allowed? | When does it run? |
|---|---|---|---|
if |
yes | exactly 1, at the start | when its condition is True |
elif |
yes | 0 or more, in the middle | when every branch above was False and its own condition is True |
else |
no | 0 or 1, at the end | when every branch above was False |
if name:: empty or not
Remember episode 3? An empty string counts as False, and any other text counts as True. Values that act like True in an if are called truthy; values that act like False are falsy. So you can write just if name:, meaning "if name is not empty".
name = input("Name: ").strip()
if name:
print(f"Welcome, {name}!")
else:
print("Please type your name")
| Input | Output |
|---|---|
Ravi |
Name: Welcome, Ravi! |
| three spaces | Name: Please type your name |
.strip() (episode 5) removes the spaces, leaving an empty string "", which is falsy. This is the Pythonic way to check for empty input. Pythonic means "the way experienced Python programmers write it". if name: is preferred over if name != "":, and if not name: over if name == "":.
Falsy values: 0, 0.0, "", None, and empty collections like []. Everything else, including " " (a space) and "False" (a 5-letter string), is truthy.
Nested if
Decisions can sit inside decisions. At the cinema: does the person have a ticket? If yes, a second question: are they 18 or older, for an A-rated film? An if inside another if is called a nested if, and the inner one is indented one more level (8 spaces).
has_ticket = True
age = 15
if has_ticket:
if age >= 18:
print("Enjoy the movie")
else:
print("A-rated: adults only")
else:
print("Buy a ticket first")
Output: A-rated: adults only
Each else belongs to the if it lines up with: the inner else (4 spaces) goes with if age >= 18, the outer one (0 spaces) with if has_ticket.
Flatten it with and
Nested ifs get deep fast. When you only need a yes or no, combine the questions with and (episode 4):
has_ticket = True
age = 15
if has_ticket and age >= 18:
print("Enjoy the movie")
else:
print("Sorry, no entry")
Output: Sorry, no entry
Same decision, one level, easier to read. "Flat is better than nested" is one of the official design rules of Python (the Zen of Python; type import this to read them all). Keep the nested version when each "no" needs its own message.
The one-line if/else (conditional expression)
When an if only chooses between two values, Python has a one-line form:
age = int(input("Age: "))
status = "adult" if age >= 18 else "minor"
print(status)
Input 15 → Age: minor; input 18 → Age: adult
This is a conditional expression (other languages call it the ternary operator, because it has three parts). It reads almost like English: value1 if condition else value2. An expression is anything that produces a value, so you can put it on the right of = or inside print(). Use it for short choices only; for anything longer, use a normal if/else.
Mistake 4: else that doesn't line up
cups = 3
if cups > 10:
print("bulk")
else:
print("normal")
File "main.py", line 4
else:
^
IndentationError: unindent does not match any outer indentation level
"Unindent" means moving back to the left. The else moved back to 2 spaces, but no earlier line starts at 2 spaces, so Python can't tell which if it belongs to. else must line up exactly with its if. Python doesn't guess: keep your spaces consistent (and don't mix tabs and spaces).
The opposite mistake, indenting a line that belongs to no block (cups = 3 then print(cups)), gives IndentationError: unexpected indent on line 2.
Common mistakes (and the real error messages)
| Mistake | Error | Why | Fix |
|---|---|---|---|
if cups > 10 |
SyntaxError: expected ':' |
the if line needs a colon |
if cups > 10: |
if cups > 10: then bill = bill * 0.9 at the left edge |
IndentationError: expected an indented block after 'if' statement on line 3 |
the block must be indented | 4 spaces before bill |
if cups = 12: |
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='? |
= stores, == compares |
if cups == 12: |
if marks >= 50: ... elif marks >= 90: |
no error: 95 gets Grade C |
the first True branch wins |
strictest condition first |
else: indented by 2 spaces |
IndentationError: unindent does not match any outer indentation level |
else not lined up with its if |
else at the same level as if |
print(cups) with no if above |
IndentationError: unexpected indent |
indented line that belongs to no block | remove the spaces |
else cups <= 10: |
SyntaxError: expected ':' |
else takes no condition |
else: (or elif cups <= 10:) |
three separate ifs for grades |
no error: Grade A, Grade B, Grade C |
each if is a separate question |
use elif |
Mini project: cinema ticket counter
The rules:
- Under 3: free
- Under 12: ₹100
- 60 and above: ₹120
- Everyone else: ₹200
- Weekend (sat/sun): + ₹50, but babies stay free
The age rules are one elif chain (a person gets exactly one age price), but the weekend is a separate question, so it gets its own if.
# Mini project: cinema ticket counter
age = int(input("Age: "))
day = input("Day: ").strip().lower()
if age < 3:
price = 0
elif age < 12:
price = 100
elif age >= 60:
price = 120
else:
price = 200
if price > 0 and (day == "sat" or day == "sun"):
price += 50
print(f"Ticket: Rs {price}")
Input 65 then SUN (one answer per line) → Age: Day: Ticket: Rs 170
₹120 for a senior, plus ₹50 for the weekend. .strip().lower() turned SUN into sun, so the weekend check matched.
Why the brackets? and is worked out before or (episode 4). Without brackets, Python would read price > 0 and day == "sat" or day == "sun" as (price > 0 and day == "sat") or day == "sun", so a baby on Sunday would be charged. The brackets make it "paid ticket and (Saturday or Sunday)". More runs:
| Age | Day | Output |
|---|---|---|
1 |
sat |
Age: Day: Ticket: Rs 0 |
8 |
sat |
Age: Day: Ticket: Rs 150 |
30 |
mon |
Age: Day: Ticket: Rs 200 |
25 |
sunday |
Age: Day: Ticket: Rs 200 |
Notice the last row: "sunday" is not "sun", so no weekend charge. The program only understands exactly what you told it.
Challenge from the video: ask "Student? (yes/no)" and take ₹30 off for students.
Practice
- Even or odd (homework): read a number and say whether it is even or odd.
Solution
n = int(input("Number: "))
if n % 2 == 0:
print(n, "is even")
else:
print(n, "is odd")
Input 7 → Number: 7 is odd; input -4 → Number: -4 is even; input 0 → Number: 0 is even
% gives the remainder (episode 4). A number is even when the remainder after dividing by 2 is 0.
- Biggest of three (homework): read three numbers and print the biggest.
Solution
a = int(input("First: "))
b = int(input("Second: "))
c = int(input("Third: "))
if a >= b and a >= c:
biggest = a
elif b >= c:
biggest = b
else:
biggest = c
print("Biggest:", biggest)
Input 12, 45, 7 → First: Second: Third: Biggest: 45; input 9, 9, 3 → First: Second: Third: Biggest: 9
>= makes ties work. (Python's built-in max(a, b, c) does the same.)
- Electricity bill with slabs (homework): the first 100 units cost ₹3 each, units 101-200 cost ₹5 each, and every unit above 200 costs ₹8.
Solution
units = int(input("Units used: "))
if units <= 100:
bill = units * 3
elif units <= 200:
bill = 100 * 3 + (units - 100) * 5
else:
bill = 100 * 3 + 100 * 5 + (units - 200) * 8
print(f"Bill: Rs {bill}")
Input 80 → Units used: Bill: Rs 240; input 150 → Units used: Bill: Rs 550; input 250 → Units used: Bill: Rs 1200
A slab is a range with its own rate. 150 units = 100 × 3 + 50 × 5 = 300 + 250 = 550.
- Login check (homework): username
raju, passwordchai123. Print a different message for a wrong password and an unknown user.
Solution
username = input("Username: ").strip()
password = input("Password: ")
if username == "raju" and password == "chai123":
print("Login successful. Welcome, Raju!")
elif username == "raju":
print("Wrong password")
else:
print("Unknown user")
Inputs raju/chai123 → Username: Password: Login successful. Welcome, Raju!; raju/chai → Username: Password: Wrong password; priya/abc → Username: Password: Unknown user
Quick quiz
What does this print?
x = 15
if x > 10:
print("A")
elif x > 5:
print("B")
else:
print("C")
A) A B) A and B C) B D) A, B and C
Answer
A) A, just A. x > 10 is True, so A prints and the whole chain stops. The elif and else are skipped, even though x > 5 is also True.
Interview questions
- How does Python know which lines belong to an
if? By indentation. The lines after the colon that are indented more than theifform its block; the first line back at theif's level ends it. Python has no curly brackets for blocks. - What is the difference between several
ifs and anif/elifchain? Separateifs are all checked, so several can run. In anif/elif/elsechain, conditions are checked top to bottom and only the firstTruebranch runs. - What is the difference between
=and==?=assigns (stores) a value;==compares two values and givesTrue/False.if x = 5:is aSyntaxError. - Which values are falsy in Python?
False,None,0,0.0,"", and empty collections ([],(),{},set()). Everything else is truthy, soif name:checks for a non-empty string. - What is a conditional expression? Python's ternary form:
a if condition else b. It produces one of two values, e.g.status = "adult" if age >= 18 else "minor". - Does Python have a
switchstatement? Not a classicswitch;if/elif/elseis the usual choice. Since Python 3.10 there ismatch/case(structural pattern matching), which can play a similar role.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Condition | A question whose answer is True or False |
cups > 10 |
if statement |
Runs a block only when its condition is True |
if cups > 10: |
| Colon | : at the end of an if/elif/else line; "the block starts here" |
else: |
| Indentation | Spaces at the start of a line; Python uses 4 per level | bill = bill * 0.9 |
| Block | Lines with the same indentation that run or are skipped together | the 2 lines under if cups > 10: |
| Straight-line code | Code that runs every line, top to bottom, with no choices | the first discount program |
else |
The other road: runs when nothing above was True; no condition |
else: |
elif |
"else if": checked only if every branch above was False |
elif marks >= 75: |
| Branch | One of the possible roads in an if/elif/else |
the Grade B part |
| Chain | An if followed by elifs and maybe an else; first True wins |
the grade calculator |
| Catch-all | A final else that handles every remaining case |
else: print("Fail, try again") |
| Truthy / falsy | Values that act like True / False in an if |
"Ravi" / "" |
| Pythonic | Written the way experienced Python programmers write it | if name: instead of if name != "": |
| Nested if | An if inside another if's block |
if has_ticket: then if age >= 18: |
| Flatten | Replace nesting with one condition joined by and/or |
if has_ticket and age >= 18: |
| Expression | Any piece of code that produces a value | cups * 12 |
| Conditional expression / ternary | One-line choice between two values | "adult" if age >= 18 else "minor" |
| SyntaxError | Code that breaks Python's grammar; nothing runs | if cups > 10 (no colon) |
| IndentationError | A SyntaxError about wrong or missing indentation | unexpected indent |
| Unindent | Moving a line back to the left to end a block | print("Pay:", bill) after the if block |
= vs == |
= stores a value, == compares two values |
x = 12 / x == 12 |
| Slab | A range of values with its own rate | units 101-200 at ₹5 |
Summary
if condition:runs the indented block only when the condition isTrue; otherwise it is skipped.- The
ifline ends with a colon, and the block is indented by 4 spaces. Same block = same indentation, always. =stores,==compares.if x = 12:is aSyntaxErrorand Python suggests==.else:is the other road, has no condition, and withif/elseexactly one road runs.elifchecks in order and the firstTruewins, so put the strictest condition first and finish with anelsecatch-all.if name:is the Pythonic check for non-empty text;"",0andNoneare falsy.- Nested ifs work, but flat is better: join questions with
and. For two values, usea if condition else b. - Indentation errors:
expected an indented block,unexpected indent,unindent does not match any outer indentation level.
Next episode: while loops.