Week 2: Conditionals & Branching

4158 words
21 min read
2026-09-12T00:00:00.000Z
Python Week 1: the first filter for runtime behavior
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**.

Visual strip

Relevant recall pieces for this note

Open gallery

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:
python
statement_1
statement_2
statement_3
all execute in sequence.
Conditionals introduce branching:
python
if condition:
    do_this
else:
    do_that
Core ideas:
  • Boolean expressions
  • comparison operators
  • if
  • if ... else
  • if ... elif ... else
  • nested conditionals
  • logical operators
  • truth values
  • branch tracing
  • boundary conditions
  • common conditional bugs
The main mental model is:
evaluate condition→choose branch→continue\boxed{ \text{evaluate condition} \rightarrow \text{choose branch} \rightarrow \text{continue} }

1. What is a condition?

A condition is an expression that evaluates to either:
python
True
or:
python
False
Example:
python
age >= 18
If:
python
age = 20
then:
python
age >= 18
evaluates to:
python
True

2. Boolean expressions

A Boolean expression has a truth value.
Examples:
python
5 > 2
3 == 3
10 < 4
Results:
text
True
True
False

3. Comparison operators

The main comparison operators are:
OperatorMeaning
==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

python
x = 5
means:
store 5 in x

Equality test

python
x == 5
means:
is x equal to 5?
The second evaluates to a Boolean.

5. Example

python
x = 10

print(x == 10)
print(x > 20)
Output:
text
True
False

6. Basic if

Syntax:
python
if condition:
    statement
Example:
python
age = int(input())

if age >= 18:
    print("Adult")
The print runs only if the condition is true.

7. If condition is false

Input:
text
15
Condition:
python
15 >= 18
is:
python
False
So:
python
print("Adult")
is skipped.
Execution then continues after the if block.

8. Indentation matters

Python uses indentation to define blocks.
Correct:
python
if x > 0:
    print("Positive")
    print("Done checking")
Both indented statements belong to the if.

9. Outside the block

python
if 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:
python
if 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.
python
if condition:
    branch_A
else:
    branch_B
Example:
python
age = int(input())

if age >= 18:
    print("Adult")
else:
    print("Minor")

12. Mutual exclusivity

With:
python
if ...:
    ...
else:
    ...
exactly one branch executes.
If condition is true:
text
if branch
runs.
If false:
text
else branch
runs.
Not both.

13. Example trace

python
x = 7

if x % 2 == 0:
    print("Even")
else:
    print("Odd")
Evaluate:
7 mod 2=17 \bmod 2 = 1
So:
python
7 % 2 == 0
is false.
Output:
text
Odd

14. Even / odd test

For integer n:
python
n % 2 == 0
means even.
python
n % 2 != 0
means odd.
This is one of the most common early conditional patterns.

15. elif

For more than two cases:
python
if condition_1:
    ...
elif condition_2:
    ...
else:
    ...
Python checks conditions from top to bottom.

16. Example grading rule

python
marks = 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:
python
marks = 95
Check:
python
marks >= 90
True.
Python executes:
python
print("A")
and skips every later elif / else branch.

18. Why order matters

Bad:
python
if marks >= 40:
    print("Pass")
elif marks >= 90:
    print("Excellent")
For:
python
marks = 95
first condition is already true.
So "Excellent" is never reached.
More specific/higher threshold conditions usually need to come first.

19. Correct ordering

python
if 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:
python
if x > 0:
    print("Positive")

if x > 10:
    print("Large")
For:
python
x = 20
both messages print.

21. if/elif

python
if x > 0:
    print("Positive")
elif x > 10:
    print("Large")
For:
python
x = 20
only "Positive" prints.
Once the first branch succeeds, the chain stops.

22. Use independent ifs when multiple conditions may all matter

Example:
python
if age >= 18:
    print("Adult")

if age >= 60:
    print("Senior")
For:
python
age = 65
both statements may legitimately apply.

23. Use elif for alternative categories

Example:
python
if 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.
python
if age >= 18:
    if has_id:
        print("Allowed")
The inner condition is checked only if the outer condition is true.

25. Example

python
age = 20
has_id = True

if age >= 18:
    if has_id:
        print("Entry allowed")
    else:
        print("ID required")
else:
    print("Too young")
Trace:
text
age >= 18 → True
has_id → True
Output:
text
Entry allowed

26. Nested vs combined condition

This:
python
if age >= 18:
    if has_id:
        print("Allowed")
can often be expressed as:
python
if age >= 18 and has_id:
    print("Allowed")
Both require both conditions to hold.

27. Logical and

Python:
python
A and B
is true only when both are true.
Truth table:
ABA and B
FalseFalseFalse
FalseTrueFalse
TrueFalseFalse
TrueTrueTrue

28. Example with and

python
age = 20
marks = 80

if age >= 18 and marks >= 60:
    print("Eligible")
Both conditions are true, so output:
text
Eligible

29. Range check

To check:
10≤x≤2010 \le x \le 20
you can write:
python
x >= 10 and x <= 20
Python also supports chained comparison syntax:
python
10 <= x <= 20
Both express the same intended condition here.

30. Logical or

Python:
python
A or B
is true if at least one condition is true.
Truth table:
ABA or B
FalseFalseFalse
FalseTrueTrue
TrueFalseTrue
TrueTrueTrue

31. Example with or

python
day = input()

if day == "Saturday" or day == "Sunday":
    print("Weekend")
Either value satisfies the condition.

32. Outside-range condition

To test whether:
x<10x<10
or:
x>20,x>20,
write:
python
if x < 10 or x > 20:
    print("Outside")

33. Logical not

not reverses a Boolean value.
python
not True
gives:
python
False
and:
python
not False
gives:
python
True

34. Example

python
logged_in = False

if not logged_in:
    print("Please log in")
Since:
python
not False
is true, the message prints.

35. Compound conditions

Example:
python
if 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:
text
not
and
or
have different precedence.
But for study/exams, parentheses are often the safest way to make intended grouping obvious.
Compare:
python
A 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:
python
A and B
if A is false, the whole expression must be false.
So B need not be evaluated.
For:
python
A or B
if A is true, the whole expression must be true.

38. Why short-circuiting can matter

Example:
python
if x != 0 and 10 / x > 2:
    ...
If:
python
x = 0
the first condition is false.
Python does not need to evaluate:
python
10 / x
which would otherwise cause division by zero.

39. String comparison

Conditions can compare strings:
python
name == "Alice"
Example:
python
answer = input()

if answer == "yes":
    print("Accepted")
String comparison is exact unless you explicitly transform the string.

40. Case sensitivity

These strings are different:
text
yes
Yes
YES
So:
python
answer == "yes"
does not automatically accept "YES".

41. Normalizing input

One common pattern:
python
answer = input().lower()

if answer == "yes":
    print("Accepted")
Then:
text
YES
Yes
yes
all become:
text
yes
before comparison.

42. Boolean variable directly as condition

If:
python
is_valid = True
you can write:
python
if is_valid:
    print("Valid")
You do not need:
python
if 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:
python
x = 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

python
a = float(input())
b = float(input())

if a > b:
    print(a)
else:
    print(b)
But note: when:
python
a == b
the else branch prints b, which still gives the correct maximum value.

46. Maximum of three numbers

A simple approach:
python
a = 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

python
if 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:
text
if 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:
python
marks >= 40
Not:
python
marks > 40
because:
4040
itself should pass.

50. Inclusive vs exclusive boundary

Compare:
python
x >= 10
includes 10.
python
x > 10
does not.
Small operator differences often determine correctness at boundaries.

51. Interval example

Suppose allowed range is:
0≤x≤100.0\leq x\leq100.
Correct:
python
if 0 <= x <= 100:
    print("Valid")
Values:
text
0
100
must both be included.

52. Invalid range

python
if x < 0 or x > 100:
    print("Invalid")
This is the complement of:
python
0 <= x <= 100

53. De Morgan intuition

The negation of:
python
A and B
corresponds logically to:
python
not A or not B
And the negation of:
python
A or B
corresponds to:
python
not A and not B
These are De Morgan's laws.
They can help simplify conditional logic.

54. Example

Inside interval:
python
x >= 10 and x <= 20
Not inside interval:
python
x < 10 or x > 20
This is often cleaner than wrapping the first condition in not.

55. Conditional assignment pattern

Example:
python
if 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:
python
if score >= 40:
    print("Pass")
    print("Result processed")
else:
    print("Fail")
    print("Result processed")
you can write:
python
if score >= 40:
    print("Pass")
else:
    print("Fail")

print("Result processed")
Avoid duplicating common work when unnecessary.

57. Nested branch trace

Consider:
python
x = 12
y = 5

if x > 10:
    if y > 10:
        print("A")
    else:
        print("B")
else:
    print("C")
Trace:
text
x > 10 → True
y > 10 → False
Output:
text
B

58. elif trace

python
x = 15

if x > 20:
    print("A")
elif x > 10:
    print("B")
elif x > 5:
    print("C")
else:
    print("D")
Evaluate:
text
x > 20 → False
x > 10 → True
Stop.
Output:
text
B
Even though:
python
x > 5
is also true, it is never checked.

59. Independent if trace

python
x = 15

if x > 20:
    print("A")

if x > 10:
    print("B")

if x > 5:
    print("C")
Outputs:
text
B
C
because each condition is evaluated independently.

60. Conditional expressions should be read literally

Suppose:
python
if 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:
python
x < 0 and x > 10
cannot hold for any real x.
Such conditions are useful to spot during debugging.

62. Almost-always-true condition

Example:
python
x >= 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:
python
x >= 10 and x <= 20
or:
python
10 <= x <= 20

Common mistake:
= inside comparison intent
Wrong:
python
if x = 5:
because = is assignment syntax, not equality comparison.
Correct:
python
if x == 5:

Common mistake: forgetting colon
Python conditional headers need :.
Correct:
python
if x > 0:
    print(x)

Common mistake: bad indentation
python
if x > 0:
print("Positive")
is invalid because the branch body must be indented.

Common mistake: dangling logic due to indentation
python
if 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 if
This:
python
if 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:
python
if age >= 18:
    print("Adult")
elif age >= 65:
    print("Senior")
Senior is unreachable.
Correct order:
python
if age >= 65:
    print("Senior")
elif age >= 18:
    print("Adult")

Common mistake: gaps between conditions
Suppose:
python
if score > 80:
    print("High")
elif score < 50:
    print("Low")
What happens for:
50≤score≤80?50\leq score\leq80?
Nothing.
That may be intended or may be a bug.
Check whether the cases are exhaustive.

Common mistake: duplicate conditions
python
if 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:
python
if age >= 18 and (citizen or resident):
Without careful grouping, logic can mean something different.

Common mistake with strings and
or
A classic Python bug:
python
if answer == "yes" or "y":
This does not correctly mean:
answer equals "yes" or answer equals "y"
Correct:
python
if answer == "yes" or answer == "y":
or:
python
if 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
python
age = input()

if age >= 18:
age is text, while 18 is an integer.
For numeric comparison, convert:
python
age = int(input())

75. Validation with conditionals

Suppose age should be non-negative:
python
age = int(input())

if age >= 0:
    print("Valid")
else:
    print("Invalid")
Conditionals allow programs to enforce constraints.

76. Example: division safely

python
a = 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:
b≠0b\neq0
is a precondition.
Week 2 lets the program explicitly test it:
python
if b != 0:
This is a major transition from assumptions to controlled behaviour.

78. Boolean variable example

python
temperature = 35

is_hot = temperature > 30

print(is_hot)
Output:
text
True
Then:
python
if is_hot:
    print("Hot")
Conditions themselves can be stored as values.

79. Reusing Boolean expressions

Instead of repeating:
python
age >= 18 and has_id
you can conceptually store:
python
eligible = age >= 18 and has_id
then:
python
if eligible:
    ...
This can improve readability.

80. Conditional flowchart mental model

text
          condition?
          /       \
       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:
python
if ...
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:
python
age = 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:
python
elif age < 18:
we already know:
python
age < 5
was false.
Therefore:
age≥5.age\geq5.
So the second branch effectively means:
5≤age<18.5\leq age<18.
Earlier branches provide context.

84. Worked example — largest of three

python
a = 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:
a+b>ca+b>c a+c>ba+c>b b+c>a.b+c>a.
Python:
python
if 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:
python
x = 8
y = 12

if x > 5:
    y = y + 3

if y > 10:
    x = x * 2
else:
    x = x - 1

print(x, y)
Start:
x=8, y=12.x=8,\ y=12.
First condition:
8>58>5
true.
So:
y=15.y=15.
Second condition:
15>1015>10
true.
So:
x=16.x=16.
Output:
text
16 15

87. Trace branch state, not just conditions

For conditional code, track:
StepConditionResultState change
1x > 5Truey = 15
2y > 10Truex = 16
A previous branch may change values used by later conditions.

88. Conditions can depend on updated state

Example:
python
x = 5

if x == 5:
    x = 10

if x == 10:
    print("Yes")
The second condition uses the new value.
Output:
text
Yes

89. Conditionals do not loop

An if checks a condition once when execution reaches it.
python
if 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:
python
if 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:
  1. Write current variable values.
  2. Evaluate the first condition as exactly True or False.
  3. Enter only the appropriate branch.
  4. Apply assignments in that branch.
  5. Skip branches that do not execute.
  6. Continue with updated state.
  7. Repeat for every later condition.
  8. 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

python
if condition:
    statements
python
if condition:
    statements
else:
    statements
python
if condition_1:
    statements
elif condition_2:
    statements
else:
    statements
Logical operators:
python
and
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 one if/elif/else chain?
  • Did I use and vs or correctly?
  • 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:
  1. Evaluate Boolean expressions.
  2. Use all major comparison operators.
  3. Distinguish = from ==.
  4. Write simple if statements.
  5. Use if/else.
  6. Use if/elif/else.
  7. Understand first-true-branch behaviour.
  8. Distinguish independent ifs from elif.
  9. Trace nested conditionals.
  10. Use and, or, and not.
  11. Write correct range checks.
  12. Handle inclusive/exclusive boundaries.
  13. Validate input using conditions.
  14. Avoid division-by-zero using conditions.
  15. Recognize impossible/overlapping conditions.
  16. Understand how branch execution changes later program state.
  17. 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 '', and None evaluate 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 of or is 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

Active Recall Session

Document outline

Keep your place and jump directly to a heading.

Table of contents

No note selected

Open a chapter to see its outline, backlinks, and sources here.