Week 2: Conditionals & Branching
4158 words
21 min read
2026-09-12T00:00:00.000Z
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
Boolean expressions, relational operators, logical operators, if-elif-else branching, and short-circuit evaluation. # Programming in Python — Week 2: Conditionals & Branching The official IITM syllabus lists **Week 2: Conditionals**.

Programming in Python — Week 2: Conditionals & Branching
The official IITM syllabus lists Week 2: Conditionals.
This week is about making Python choose different paths depending on whether a condition is true or false.
TL;DR
Until now:
pythonstatement_1 statement_2 statement_3
all execute in sequence.
Conditionals introduce branching:
pythonif condition: do_this else: do_that
Core ideas:
- Boolean expressions
- comparison operators
ifif ... elseif ... elif ... else- nested conditionals
- logical operators
- truth values
- branch tracing
- boundary conditions
- common conditional bugs
The main mental model is:
1. What is a condition?
A condition is an expression that evaluates to either:
pythonTrue
or:
pythonFalse
Example:
pythonage >= 18
If:
pythonage = 20
then:
pythonage >= 18
evaluates to:
pythonTrue
2. Boolean expressions
A Boolean expression has a truth value.
Examples:
python5 > 2 3 == 3 10 < 4
Results:
textTrue True False
3. Comparison operators
The main comparison operators are:
| Operator | Meaning |
|---|---|
== | equal to |
!= | not equal to |
> | greater than |
< | less than |
>= | greater than or equal to |
<= | less than or equal to |
4. = vs ==
This distinction is essential.
Assignment
pythonx = 5
means:
store 5 inx
Equality test
pythonx == 5
means:
isxequal to 5?
The second evaluates to a Boolean.
5. Example
pythonx = 10 print(x == 10) print(x > 20)
Output:
textTrue False
6. Basic if
Syntax:
pythonif condition: statement
Example:
pythonage = int(input()) if age >= 18: print("Adult")
The print runs only if the condition is true.
7. If condition is false
Input:
text15
Condition:
python15 >= 18
is:
pythonFalse
So:
pythonprint("Adult")
is skipped.
Execution then continues after the
if block.8. Indentation matters
Python uses indentation to define blocks.
Correct:
pythonif x > 0: print("Positive") print("Done checking")
Both indented statements belong to the
if.9. Outside the block
pythonif x > 0: print("Positive") print("Finished")
Finished prints regardless of whether the condition is true.This distinction is purely controlled by indentation.
10. Common indentation bug
Consider:
pythonif x > 0: print("Positive") print("Greater than zero")
The second line is not inside the
if.So it always runs.
11. if ... else
Use
else when exactly one of two branches should execute.pythonif condition: branch_A else: branch_B
Example:
pythonage = int(input()) if age >= 18: print("Adult") else: print("Minor")
12. Mutual exclusivity
With:
pythonif ...: ... else: ...
exactly one branch executes.
If condition is true:
textif branch
runs.
If false:
textelse branch
runs.
Not both.
13. Example trace
pythonx = 7 if x % 2 == 0: print("Even") else: print("Odd")
Evaluate:
So:
python7 % 2 == 0
is false.
Output:
textOdd
14. Even / odd test
For integer
n:pythonn % 2 == 0
means even.
pythonn % 2 != 0
means odd.
This is one of the most common early conditional patterns.
15. elif
For more than two cases:
pythonif condition_1: ... elif condition_2: ... else: ...
Python checks conditions from top to bottom.
16. Example grading rule
pythonmarks = int(input()) if marks >= 90: print("A") elif marks >= 75: print("B") elif marks >= 60: print("C") else: print("D")
17. First true branch wins
Suppose:
pythonmarks = 95
Check:
pythonmarks >= 90
True.
Python executes:
pythonprint("A")
and skips every later
elif / else branch.18. Why order matters
Bad:
pythonif marks >= 40: print("Pass") elif marks >= 90: print("Excellent")
For:
pythonmarks = 95
first condition is already true.
So
"Excellent" is never reached.More specific/higher threshold conditions usually need to come first.
19. Correct ordering
pythonif marks >= 90: print("Excellent") elif marks >= 40: print("Pass") else: print("Fail")
Now 95 correctly reaches
"Excellent".20. Independent ifs vs elif
These are different:
pythonif x > 0: print("Positive") if x > 10: print("Large")
For:
pythonx = 20
both messages print.
21. if/elif
pythonif x > 0: print("Positive") elif x > 10: print("Large")
For:
pythonx = 20
only
"Positive" prints.Once the first branch succeeds, the chain stops.
22. Use independent ifs when multiple conditions may all matter
Example:
pythonif age >= 18: print("Adult") if age >= 60: print("Senior")
For:
pythonage = 65
both statements may legitimately apply.
23. Use elif for alternative categories
Example:
pythonif temperature < 10: print("Cold") elif temperature < 25: print("Moderate") else: print("Hot")
Each temperature belongs to one category.
24. Nested conditionals
An
if can exist inside another if.pythonif age >= 18: if has_id: print("Allowed")
The inner condition is checked only if the outer condition is true.
25. Example
pythonage = 20 has_id = True if age >= 18: if has_id: print("Entry allowed") else: print("ID required") else: print("Too young")
Trace:
textage >= 18 → True has_id → True
Output:
textEntry allowed
26. Nested vs combined condition
This:
pythonif age >= 18: if has_id: print("Allowed")
can often be expressed as:
pythonif age >= 18 and has_id: print("Allowed")
Both require both conditions to hold.
27. Logical and
Python:
pythonA and B
is true only when both are true.
Truth table:
| A | B | A and B |
|---|---|---|
| False | False | False |
| False | True | False |
| True | False | False |
| True | True | True |
28. Example with and
pythonage = 20 marks = 80 if age >= 18 and marks >= 60: print("Eligible")
Both conditions are true, so output:
textEligible
29. Range check
To check:
you can write:
pythonx >= 10 and x <= 20
Python also supports chained comparison syntax:
python10 <= x <= 20
Both express the same intended condition here.
30. Logical or
Python:
pythonA or B
is true if at least one condition is true.
Truth table:
| A | B | A or B |
|---|---|---|
| False | False | False |
| False | True | True |
| True | False | True |
| True | True | True |
31. Example with or
pythonday = input() if day == "Saturday" or day == "Sunday": print("Weekend")
Either value satisfies the condition.
32. Outside-range condition
To test whether:
or:
write:
pythonif x < 10 or x > 20: print("Outside")
33. Logical not
not reverses a Boolean value.pythonnot True
gives:
pythonFalse
and:
pythonnot False
gives:
pythonTrue
34. Example
pythonlogged_in = False if not logged_in: print("Please log in")
Since:
pythonnot False
is true, the message prints.
35. Compound conditions
Example:
pythonif age >= 18 and (country == "India" or country == "Nepal"): print("Eligible")
Parentheses make grouping clear.
Always reason about compound Boolean expressions carefully.
36. Boolean precedence
Broadly:
textnot and or
have different precedence.
But for study/exams, parentheses are often the safest way to make intended grouping obvious.
Compare:
pythonA or B and C
with:
python(A or B) and C
They need not mean the same thing.
37. Short-circuit evaluation
Python may stop evaluating a Boolean expression once the result is already known.
For:
pythonA and B
if
A is false, the whole expression must be false.So
B need not be evaluated.For:
pythonA or B
if
A is true, the whole expression must be true.38. Why short-circuiting can matter
Example:
pythonif x != 0 and 10 / x > 2: ...
If:
pythonx = 0
the first condition is false.
Python does not need to evaluate:
python10 / x
which would otherwise cause division by zero.
39. String comparison
Conditions can compare strings:
pythonname == "Alice"
Example:
pythonanswer = input() if answer == "yes": print("Accepted")
String comparison is exact unless you explicitly transform the string.
40. Case sensitivity
These strings are different:
textyes Yes YES
So:
pythonanswer == "yes"
does not automatically accept
"YES".41. Normalizing input
One common pattern:
pythonanswer = input().lower() if answer == "yes": print("Accepted")
Then:
textYES Yes yes
all become:
textyes
before comparison.
42. Boolean variable directly as condition
If:
pythonis_valid = True
you can write:
pythonif is_valid: print("Valid")
You do not need:
pythonif is_valid == True:
though it may still work.
43. Truthiness intuition
Python allows some non-Boolean values to behave as true/false in conditions.
For example, empty values often behave as false-like and non-empty values as true-like.
For now, prefer explicit conditions while learning unless the course material uses truthiness directly.
44. Positive / negative / zero
Classic three-way conditional:
pythonx = float(input()) if x > 0: print("Positive") elif x < 0: print("Negative") else: print("Zero")
These cases are:
- mutually exclusive
- exhaustive
Every real number fits exactly one.
45. Maximum of two numbers
pythona = float(input()) b = float(input()) if a > b: print(a) else: print(b)
But note: when:
pythona == b
the
else branch prints b, which still gives the correct maximum value.46. Maximum of three numbers
A simple approach:
pythona = float(input()) b = float(input()) c = float(input()) maximum = a if b > maximum: maximum = b if c > maximum: maximum = c print(maximum)
Notice these are independent
ifs, not elif.Why?
Because after updating with
b, we still need to compare c.47. Another max-of-three approach
pythonif a >= b and a >= c: print(a) elif b >= a and b >= c: print(b) else: print(c)
This uses compound conditions.
Both approaches can work.
48. Leap-year style reasoning
Conditionals are often used for rules with exceptions.
Conceptually, problems may have logic like:
textif special_case: ... elif ordinary_case: ... else: ...
The important skill is translating the verbal rule into correct Boolean structure.
49. Boundary conditions
Suppose:
Pass if marks are at least 40.
Correct:
pythonmarks >= 40
Not:
pythonmarks > 40
because:
itself should pass.
50. Inclusive vs exclusive boundary
Compare:
pythonx >= 10
includes 10.
pythonx > 10
does not.
Small operator differences often determine correctness at boundaries.
51. Interval example
Suppose allowed range is:
Correct:
pythonif 0 <= x <= 100: print("Valid")
Values:
text0 100
must both be included.
52. Invalid range
pythonif x < 0 or x > 100: print("Invalid")
This is the complement of:
python0 <= x <= 100
53. De Morgan intuition
The negation of:
pythonA and B
corresponds logically to:
pythonnot A or not B
And the negation of:
pythonA or B
corresponds to:
pythonnot A and not B
These are De Morgan's laws.
They can help simplify conditional logic.
54. Example
Inside interval:
pythonx >= 10 and x <= 20
Not inside interval:
pythonx < 10 or x > 20
This is often cleaner than wrapping the first condition in
not.55. Conditional assignment pattern
Example:
pythonif score >= 40: result = "Pass" else: result = "Fail" print(result)
The branch assigns a value, then common code uses it afterward.
56. Shared code after branches
Instead of:
pythonif score >= 40: print("Pass") print("Result processed") else: print("Fail") print("Result processed")
you can write:
pythonif score >= 40: print("Pass") else: print("Fail") print("Result processed")
Avoid duplicating common work when unnecessary.
57. Nested branch trace
Consider:
pythonx = 12 y = 5 if x > 10: if y > 10: print("A") else: print("B") else: print("C")
Trace:
textx > 10 → True y > 10 → False
Output:
textB
58. elif trace
pythonx = 15 if x > 20: print("A") elif x > 10: print("B") elif x > 5: print("C") else: print("D")
Evaluate:
textx > 20 → False x > 10 → True
Stop.
Output:
textB
Even though:
pythonx > 5
is also true, it is never checked.
59. Independent if trace
pythonx = 15 if x > 20: print("A") if x > 10: print("B") if x > 5: print("C")
Outputs:
textB C
because each condition is evaluated independently.
60. Conditional expressions should be read literally
Suppose:
pythonif x > 5 and x < 3:
This condition can never be true.
Do not mentally "fix" it.
If asked to trace, use exactly what is written.
61. Impossible conditions
Example:
pythonx < 0 and x > 10
cannot hold for any real
x.Such conditions are useful to spot during debugging.
62. Almost-always-true condition
Example:
pythonx >= 10 or x <= 20
For real numbers, this is true for essentially every
x.Why?
- values below 10 satisfy
x <= 20 - values above 20 satisfy
x >= 10 - values in between satisfy both
This is a common
and/or error.63. Correct "between 10 and 20"
Use:
pythonx >= 10 and x <= 20
or:
python10 <= x <= 20
Common mistake:
= inside comparison intentWrong:
pythonif x = 5:
because
= is assignment syntax, not equality comparison.Correct:
pythonif x == 5:
Common mistake: forgetting colon
Python conditional headers need
:.Correct:
pythonif x > 0: print(x)
Common mistake: bad indentation
pythonif x > 0: print("Positive")
is invalid because the branch body must be indented.
Common mistake: dangling logic due to indentation
pythonif x > 0: print("Positive") if x > 10: print("Large")
Here the second check happens only when
x > 0.Changing indentation changes program meaning.
Common mistake:
elif after separate completed ifThis:
pythonif x > 0: ... if x > 10: ... elif x > 5: ...
means the
elif belongs to the second if, not the first.Read block structure carefully.
Common mistake: overlapping categories ordered badly
Suppose:
pythonif age >= 18: print("Adult") elif age >= 65: print("Senior")
Senior is unreachable.Correct order:
pythonif age >= 65: print("Senior") elif age >= 18: print("Adult")
Common mistake: gaps between conditions
Suppose:
pythonif score > 80: print("High") elif score < 50: print("Low")
What happens for:
Nothing.
That may be intended or may be a bug.
Check whether the cases are exhaustive.
Common mistake: duplicate conditions
pythonif x > 10: print("A") elif x > 10: print("B")
The second branch can never execute.
Common mistake: wrong Boolean grouping
Suppose intended:
adult and either citizen or resident
Correct:
pythonif age >= 18 and (citizen or resident):
Without careful grouping, logic can mean something different.
Common mistake with strings and
orA classic Python bug:
pythonif answer == "yes" or "y":
This does not correctly mean:
answer equals"yes"or answer equals"y"
Correct:
pythonif answer == "yes" or answer == "y":
or:
pythonif answer in ("yes", "y"):
The second form uses collection membership, which will become more natural once collections are formally covered.
Common mistake: compare numerical string to number
pythonage = input() if age >= 18:
age is text, while 18 is an integer.For numeric comparison, convert:
pythonage = int(input())
75. Validation with conditionals
Suppose age should be non-negative:
pythonage = int(input()) if age >= 0: print("Valid") else: print("Invalid")
Conditionals allow programs to enforce constraints.
76. Example: division safely
pythona = float(input()) b = float(input()) if b != 0: print(a / b) else: print("Cannot divide by zero")
The conditional prevents a runtime error.
77. Preconditions become executable checks
Week 1 might say:
is a precondition.
Week 2 lets the program explicitly test it:
pythonif b != 0:
This is a major transition from assumptions to controlled behaviour.
78. Boolean variable example
pythontemperature = 35 is_hot = temperature > 30 print(is_hot)
Output:
textTrue
Then:
pythonif is_hot: print("Hot")
Conditions themselves can be stored as values.
79. Reusing Boolean expressions
Instead of repeating:
pythonage >= 18 and has_id
you can conceptually store:
pythoneligible = age >= 18 and has_id
then:
pythonif eligible: ...
This can improve readability.
80. Conditional flowchart mental model
textcondition? / \ True False | | branch A branch B \ / continue
This is the control-flow structure implemented by
if/else.81. Decision tree connection
A chain such as:
pythonif ... elif ... elif ... else ...
is essentially a simple decision tree expressed in Python.
That links directly back to CT Week 12.
82. Worked example — ticket price
Rules:
- age below 5 → free
- age below 18 → ₹100
- otherwise → ₹200
Python:
pythonage = int(input()) if age < 5: price = 0 elif age < 18: price = 100 else: price = 200 print(price)
83. Why second condition can just be age < 18
When Python reaches:
pythonelif age < 18:
we already know:
pythonage < 5
was false.
Therefore:
So the second branch effectively means:
Earlier branches provide context.
84. Worked example — largest of three
pythona = int(input()) b = int(input()) c = int(input()) if a >= b and a >= c: largest = a elif b >= a and b >= c: largest = b else: largest = c print(largest)
This also handles ties.
85. Worked example — valid triangle sides
For positive lengths, a triangle requires:
Python:
pythonif a > 0 and b > 0 and c > 0: if a + b > c and a + c > b and b + c > a: print("Valid") else: print("Invalid") else: print("Invalid")
This demonstrates compound and nested logic.
86. Worked trace
Program:
pythonx = 8 y = 12 if x > 5: y = y + 3 if y > 10: x = x * 2 else: x = x - 1 print(x, y)
Start:
First condition:
true.
So:
Second condition:
true.
So:
Output:
text16 15
87. Trace branch state, not just conditions
For conditional code, track:
| Step | Condition | Result | State change |
|---|---|---|---|
| 1 | x > 5 | True | y = 15 |
| 2 | y > 10 | True | x = 16 |
A previous branch may change values used by later conditions.
88. Conditions can depend on updated state
Example:
pythonx = 5 if x == 5: x = 10 if x == 10: print("Yes")
The second condition uses the new value.
Output:
textYes
89. Conditionals do not loop
An
if checks a condition once when execution reaches it.pythonif x < 10: x = x + 1
does not repeatedly increment until x reaches 10.
Repeated execution comes later with loops in Weeks 4–5. The official syllabus places Iterations and Ranges there.
90. Nested depth can become hard to read
Example:
pythonif A: if B: if C: if D: ...
This may be logically valid, but deeply nested logic can become difficult to trace.
Sometimes Boolean operators or earlier exits can simplify structure.
For now, focus on correct logic first.
91. Exam-solving workflow
For any conditional program:
- Write current variable values.
- Evaluate the first condition as exactly
TrueorFalse. - Enter only the appropriate branch.
- Apply assignments in that branch.
- Skip branches that do not execute.
- Continue with updated state.
- Repeat for every later condition.
- Record printed output separately.
92. Do not pre-evaluate future conditions
If earlier branches modify variables, later conditions must use the modified values.
Never calculate every condition using the initial state.
93. Compact syntax sheet
pythonif condition: statements
pythonif condition: statements else: statements
pythonif condition_1: statements elif condition_2: statements else: statements
Logical operators:
pythonand or not
Comparisons:
python== != > < >= <=
94. Conditional design checklist
Before finalizing a conditional, ask:
- Are boundaries correct?
- Are branches ordered correctly?
- Are cases mutually exclusive if they should be?
- Are all required cases covered?
- Should these be independent
ifs or oneif/elif/elsechain? - Did I use
andvsorcorrectly? - Are input types correct?
- Does any branch change values used later?
95. What you should actually master
By the end of Python Week 2, you should be able to:
- Evaluate Boolean expressions.
- Use all major comparison operators.
- Distinguish
=from==. - Write simple
ifstatements. - Use
if/else. - Use
if/elif/else. - Understand first-true-branch behaviour.
- Distinguish independent
ifs fromelif. - Trace nested conditionals.
- Use
and,or, andnot. - Write correct range checks.
- Handle inclusive/exclusive boundaries.
- Validate input using conditions.
- Avoid division-by-zero using conditions.
- Recognize impossible/overlapping conditions.
- Understand how branch execution changes later program state.
- Trace conditional code line-by-line.
If these are comfortable, Programming in Python Week 2 is under control.
Quick Recall & Flashcards
Test your active recall before proceeding to practice problems. Format:
Question :: Answer.- Week 2 Diagnostic: In Python, which of the following evaluates to False in a boolean context? :: Answer: C — 0, empty collections
[],{},(), empty strings'', andNoneevaluate to False. Non-empty collections like[0]and non-empty strings like'False'are truthy. - Week 2 Diagnostic: What is the value of
True or (5 / 0 == 1)? :: Answer: B — Python uses short-circuit evaluation: since the left operand oforis True, the right operand is never evaluated, avoiding ZeroDivisionError.
Practice & Self-Check
Attempt these diagnostic questions to verify your operational understanding.
1
Question 1
In Python, which of the following evaluates to False in a boolean context?
MCQ
3 Unit Assessment
A. [0]
B. 'False'
C. 0
D. -1
2
Question 2
What is the value of
True or (5 / 0 == 1)?MCQ
3 Unit Assessment
A. ZeroDivisionError
B. True
C. False
D. None