Making Decisions with if and else
Choosing what to do
Every program so far has run straight through, top to bottom. Real programs need to behave differently depending on the data. That is what if is for.
marks = 72
if marks >= 40:
print("Pass")
print("Result declared")
The structure is: the keyword if, a condition, a colon, then an indented block of statements that run only when the condition is True. The unindented line afterwards runs either way.
The condition is any expression that produces True or False — usually a comparison, as covered in the operators tutorial.
if / else
else supplies an alternative block for when the condition is False. Exactly one of the two blocks runs.
marks = 33
if marks >= 40:
print("Pass")
else:
print("Fail")
print("Re-examination in June")
print("Done")
else takes no condition of its own — it means "in every other case" — so it is written as just else:.
if / elif / else
When there are more than two outcomes, chain them with elif (short for "else if"). Python checks each condition in order and runs the block for the first one that is true, then skips the rest entirely.
marks = 78
if marks >= 90:
grade = "O"
elif marks >= 80:
grade = "A"
elif marks >= 70:
grade = "B"
elif marks >= 60:
grade = "C"
elif marks >= 40:
grade = "D"
else:
grade = "F"
print(f"Marks: {marks}, Grade: {grade}")
Order matters enormously here. Because the first true condition wins, you must go from the most specific or highest boundary downwards. If you had written if marks >= 40 first, then 78 would match it and every student above 40 would get a D.
You can have as many elif branches as you need. The else at the end is optional, but including it is usually wise — it forces you to decide what happens in cases you did not plan for.
Why Python cares about indentation
In C, Java and JavaScript, blocks are marked by curly braces { }, and indentation is only a convention for human readers. Python has no braces. Indentation is the syntax.
Compare these two:
marks = 20
if marks >= 40:
print("Pass")
print("Congratulations")
print("---")
if marks >= 40:
print("Pass")
print("Congratulations")
In the first, both prints are inside the if, so with marks of 20 neither appears. In the second, only the first print is inside; "Congratulations" is at the outer level and always runs. Nothing but whitespace distinguishes them.
This design has a real benefit: the visual structure of the code cannot disagree with what it actually does. In a brace language you can indent a line misleadingly and hide a bug. In Python that is impossible.
The rules:
- Use four spaces per level. This is the near-universal convention.
- Be consistent. Every line in the same block must have the same indentation.
- Do not mix tabs and spaces. Python 3 rejects files that mix them ambiguously, and the error is hard to see because both look identical on screen. Set your editor to insert spaces when you press Tab.
IndentationError: expected an indented block means you wrote a colon but left the next line unindented. IndentationError: unindent does not match any outer indentation level usually means inconsistent spacing. TabError means tabs and spaces are mixed. All three are fixed by making the whitespace uniform.
Nested conditions
An if can sit inside another if. Each level indents one step further.
attendance = 82
marks = 55
if attendance >= 75:
print("Attendance requirement met.")
if marks >= 40:
print("Result: Pass")
else:
print("Result: Fail - marks below 40")
else:
print("Detained: attendance below 75%.")
print("Marks are not considered.")
The inner if is only reached when the outer condition is true. That is the point of nesting: the second question only makes sense once the first is answered.
Nesting is fine one or two levels deep. Beyond that it gets hard to follow, and you can often flatten it with and:
attendance = 82
marks = 55
if attendance >= 75 and marks >= 40:
print("Pass")
elif attendance >= 75:
print("Fail - marks below 40")
else:
print("Detained - attendance below 75%")
Both versions are correct. Choose whichever states the logic more plainly for the problem at hand.
Truthiness
if does not strictly require True or False. Any value works, and Python decides whether it counts as true.
These count as false: False, 0, 0.0, "" (empty string), [] (empty list), {} (empty dictionary), and None.
Essentially everything else counts as true — any non-zero number, any non-empty string, any non-empty list.
name = ""
subjects = ["Maths", "Physics"]
count = 0
if name:
print("Name provided")
else:
print("Name is empty")
if subjects:
print(f"{len(subjects)} subjects registered")
if count:
print("Has a count")
else:
print("Count is zero")
print(bool(""), bool("0"), bool(0), bool([]))
Note bool("0") is True. The string "0" is not empty, so it is truthy, even though it looks like zero. This catches people out.
Truthiness makes if subjects: a natural way to say "if there is anything in the list". Use it for that. Do not use it for numbers where zero is a legitimate value — there, compare explicitly with if count > 0: so your intent is unambiguous.
Common mistakes
Forgetting the colon. if marks >= 40 without the trailing : gives SyntaxError: expected ':'. Every if, elif and else line ends with a colon.
Using = instead of ==. if marks = 40: is a syntax error. Comparison is ==.
Giving else a condition. else marks < 40: is invalid. Either use else: alone, or use elif marks < 40:.
Ordering elif branches wrongly. Putting the loosest condition first means it swallows every case below it. Go from the most restrictive boundary downwards.
Writing if grade == "A" or "B":. This is always true, because "B" by itself is a non-empty string and therefore truthy. Write if grade == "A" or grade == "B":, or if grade in ("A", "B"):.
Mixing tabs and spaces. The file looks correctly aligned but Python raises TabError. Configure your editor to use four spaces and re-indent the block.
Putting statements after the colon on the same line for multi-line blocks. if x > 0: print("a") print("b") does not work. Put each statement on its own indented line.
Practice
Try the decision-making exercises on the practice page.