VM-LEARNING /class.xi ·track.cs ·ch-2-8 session: 2026_27
$cd ..

~/Conditional Statements

root@vm-learning ~ $ open ch-2-8
UNIT 2 ▪ CHAPTER 8
14
Conditional Statements
if · if-else · if-elif-else · Nested if · Flowcharts · Worked Programs
Conditional statements let a program make decisions. Based on whether a condition is True or False, Python runs one block of code instead of another — or skips it altogether. Python supports three conditional forms — if, if-else, and if-elif-else — and allows any of them to be nested inside another. Conditional statements are the single biggest reason programs feel "smart" — they are what makes a program react differently to different inputs.
Three golden rules:
  • The line that opens a conditional always ends with a colon :.
  • The statements that belong to each branch must be indented — conventionally 4 spaces.
  • A condition is any expression that evaluates to a Boolean (True or False) — most often a comparison, a membership test, or a combination with and/or/not.
Learning Outcome 1: Write Python programs using if, if-else and if-elif-else statements with correct flowchart representation.

14.1 The if Statement (single branch)

The simplest conditional — run a block only when a condition is True. When the condition is False, nothing happens and execution continues after the block.

Syntax
if  condition:
    statement(s)
Flowchart — if: Start condition ? Yes statement(s) No Stop
Example — warn the user if they entered a negative age:
age = int(input("Enter age: "))

if age < 0:
    print("Age cannot be negative!")

print("Thanks for using the program.")    # always runs

14.2 The if-else Statement (two branches)

Run one block when the condition is True and a different block when it is False. Exactly one of the two blocks will execute — never both, never neither.

Syntax
if  condition:
    statements-when-True
else:
    statements-when-False
Flowchart — if-else: Start condition ? Yes True block No False block Stop
Example — even or odd:
n = int(input("Enter a number: "))

if n % 2 == 0:
    print(n, "is even")
else:
    print(n, "is odd")

14.3 The if-elif-else Statement (multi-branch)

When there are more than two possible paths, chain additional conditions with elif (short for "else-if"). Python tests each condition top-to-bottom and runs only the first branch whose condition is True; everything after that is skipped. The final else is optional and catches whatever falls through.

Syntax
if  condition1:   statement-block-1
elif  condition2:   statement-block-2
elif  condition3:   statement-block-3
  …
else:   default-block   (optional)
Flowchart — if-elif-else: Start cond₁ ? Yes block 1 No cond₂ ? Yes block 2 No cond₃ ? Yes block 3 No else block Stop
Example — assign a grade from marks:
marks = int(input("Marks (0-100): "))

if marks >= 90:
    grade = "A"
elif marks >= 75:
    grade = "B"
elif marks >= 60:
    grade = "C"
elif marks >= 33:
    grade = "D"
else:
    grade = "Fail"

print(f"Grade: {grade}")
Order matters! Python stops at the first True condition. If you had written if marks >= 33 first, every passing student — even a 98 — would be tagged "D" and the later tests would never run.
Learning Outcome 2: Explain and apply nested if statements.

14.4 Nested if — an if inside another

The body of any if / elif / else is just a block of statements — and that block may itself contain another if. This is called a nested if. Python knows which else matches which if from the indentation.

Example — is a year a leap year?
year = int(input("Year: "))

if year % 4 == 0:                       # divisible by 4?
    if year % 100 == 0:                 #   divisible by 100?
        if year % 400 == 0:             #     divisible by 400?
            print(year, "is a leap year")
        else:
            print(year, "is NOT a leap year")
    else:
        print(year, "is a leap year")
else:
    print(year, "is NOT a leap year")
Try: 2000 → leap · 1900 → NOT leap · 2024 → leap · 2023 → NOT leap.
Avoid deep nesting. The same leap-year rule fits on one line using compound conditions:
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
    print(year, "is a leap year")
else:
    print(year, "is NOT a leap year")
As a rule of thumb, more than three levels of nesting is a sign that the code should be re-organised — possibly using elif or by splitting logic into a function (Class XII).

14.5 Conditional Expression (one-line if-else)

For simple "this or that" assignments, Python offers a compact one-liner — the conditional expression (also called the ternary form):

value_if_true  if  condition  else  value_if_false
age = 17
status = "adult" if age >= 18 else "minor"
print(status)          # minor

n = -5
abs_n = n if n >= 0 else -n
print(abs_n)           # 5

Use the one-liner for a single simple decision that produces a value. For anything more complex, prefer a full if-else — it reads better.

Learning Outcome 3: Write CBSE programs — absolute value, sort 3 numbers, divisibility.

14.6 CBSE Worked Programs

Three short programs listed in the CBSE Class XI suggested practical list. Each is a classic exercise in decision-making.

14.6.1 Program 1 — Absolute Value of a Number

The absolute value of a number is its distance from zero, ignoring sign: |−7| = 7, |7| = 7, |0| = 0.

# abs_value.py — find the absolute value of a number

n = float(input("Enter a number: "))

if n >= 0:
    abs_val = n
else:
    abs_val = -n            # flip sign

print("Absolute value =", abs_val)
Sample runs:
Enter a number: -17       →  Absolute value = 17.0
Enter a number: 23.5      →  Absolute value = 23.5
Enter a number: 0         →  Absolute value = 0.0
One-liner version:
abs_val = n if n >= 0 else -n
(Python's built-in abs() does this out of the box, but CBSE wants you to write the logic yourself.)

14.6.2 Program 2 — Sort Three Numbers in Ascending Order

Read three numbers and print them in increasing order. This is a classic exercise in chained if-elif-else.

# sort3.py — sort three numbers in ascending order

a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))

if a <= b and a <= c:              # a is smallest
    small = a
    if b <= c:
        middle, large = b, c
    else:
        middle, large = c, b
elif b <= a and b <= c:            # b is smallest
    small = b
    if a <= c:
        middle, large = a, c
    else:
        middle, large = c, a
else:                             # c is smallest
    small = c
    if a <= b:
        middle, large = a, b
    else:
        middle, large = b, a

print("Ascending order:", small, middle, large)
Sample run:
a: 8
b: 3
c: 5
Ascending order: 3.0 5.0 8.0
Pythonic short-cut (for later reference):
nums = [float(input()), float(input()), float(input())]
print(sorted(nums))

14.6.3 Program 3 — Divisibility of a Number

Check whether a number is divisible by another. The test is simply: "is the remainder zero?" — i.e., n % d == 0.

# divisible.py — is n divisible by d?

n = int(input("Enter the number (n): "))
d = int(input("Enter the divisor (d): "))

if d == 0:
    print("Divisor cannot be zero.")
elif n % d == 0:
    print(n, "is divisible by", d)
else:
    print(n, "is NOT divisible by", d,
          "— remainder is", n % d)
Sample runs:
n: 100   d: 5   →  100 is divisible by 5
n:  17   d: 3   →  17 is NOT divisible by 3 — remainder is 2
n:  10   d: 0   →  Divisor cannot be zero.

14.6.4 Bonus — FizzBuzz (divisibility classic)

A famous programming puzzle that combines divisibility, if-elif-else, and a loop preview:

for n in range(1, 16):
    if n % 15 == 0:
        print("FizzBuzz")
    elif n % 3 == 0:
        print("Fizz")
    elif n % 5 == 0:
        print("Buzz")
    else:
        print(n)
Output: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

14.7 Compact Summary of the Three Forms

FormNumber of pathsRuns block if…Typical use
ifonecondition is Trueguard — warn, validate, opt-in action
if-elsetwoTrue → block A; else block Bbinary choice — pass/fail, even/odd
if-elif-elsemanyfirst True condition wins; else runs if none matchclassification — grade, tax slab, tier
Nested ifdecision inside another decisioninner if tested only when outer branch runshierarchical rules — leap year, age+id check
Conditional expressiontwo (one-line)a if cond else bshort "this or that" assignments

📌 Quick Revision — Chapter 14 at a Glance

  • Conditional statement = runs a block of code only when a condition is True.
  • Three forms:
    • if — one branch; runs the block only if the condition is True.
    • if-else — two branches; exactly one runs.
    • if-elif-else — many branches; the first True wins, the else is optional catch-all.
  • Every conditional opening line ends with :; the block below is indented.
  • A condition is any expression evaluating to a Boolean — comparisons, membership, combinations with and/or/not.
  • Order matters in if-elif-else — Python stops at the first True.
  • Nested if — an if inside another. Python matches else to if by indentation.
  • Avoid deep nesting; use compound conditions or elif to flatten.
  • Conditional expression: a if cond else b — a one-line value selector.
  • CBSE worked programs:
    • Absolute value → abs_val = n if n >= 0 else -n.
    • Sort 3 numbers → nested if-elif-else comparing pair-wise.
    • Divisibility → n % d == 0 is the test (guard against d == 0).
  • Python's built-in helpers for these tasks — abs(), sorted(), min(), max() — exist, but exams expect you to write the logic yourself.
🧠Practice Quiz — test yourself on this chapter