JESKO GARAGE All topicsViva questions ▶ Open the practice garage

Python Conditional flow statements: 9 practice problems

UNIT 1 of the free Python for AI course. Read the short theory, then solve the problems below with instant tests. Python runs in your browser.

▶ Practise Conditional flow statements nowAll topics

Theory: Conditional flow statements in Python

THEORY
------
* if / elif / else — Python picks the FIRST true branch and skips the rest.
      if marks >= 90:
          grade = "A"
      elif marks >= 75:          # only checked when the first condition was False
          grade = "B"
      else:
          grade = "C"
  ORDER MATTERS: put the most specific / highest thresholds first.
  INDENTATION (4 spaces) defines the block — there are no braces { }.

* Nested if: an if inside another if (use when a second decision depends on the first).
  Often you can flatten with `and`:   if a: if b: ...   ==   if a and b: ...

* GUARD CLAUSES (clean code): handle invalid cases first and return early.
      def fee(age):
          if age < 0:
              return None       # invalid input handled first
          ...

* CONDITIONAL EXPRESSION (ternary):   status = "adult" if age >= 18 else "minor"

* match / case (Python 3.10+, "structural pattern matching")
      match command:
          case "start" | "go":   ...      # | means OR
          case "stop":           ...
          case _:                ...      # default (wildcard)

* Truthiness in conditions:  `if items:` means "if the list is not empty".
* `pass` — empty block placeholder.   Comparing to None:  `if x is None:`

SLAB / BRACKET problems (electricity bills, income tax) are popular viva questions: the
rate applies only to the PORTION inside each slab, not the whole amount.

9 Conditional flow statements practice problems

1. Electricity Bill Slabs

Medium2 ways to solve
📤 OUTPUT: return an int, e.g. 1200. Use `return`, not print().
Real world: Your state's electricity board charges per slab:
    first 100 units  @ Rs.3,  next 100 units (101-200) @ Rs.5,  above 200 @ Rs.8
    electricity_bill(250) -> 1200   (100*3 + 100*5 + 50*8)
    electricity_bill(80)  -> 240
Solve “Electricity Bill Slabs” in your browser →

2. Traffic Light Controller — match/case

Easy3 ways to solve
📤 OUTPUT: return a str (text), e.g. 'go'. Use `return`, not print().
"red" -> "stop", "yellow" -> "slow down", "green" -> "go", anything else -> "invalid".
Case-insensitive.   traffic_action("Green") -> "go"
Ways: match/case  ·  if/elif  ·  dict lookup with .get(..., "invalid")
Solve “Traffic Light Controller — match/case” in your browser →

3. Triangle Type

Easy2 ways to solve
📤 OUTPUT: return a str (text), e.g. 'isosceles'. Use `return`, not print().
Return "invalid" (fails triangle inequality or side <= 0), "equilateral", "isosceles" or "scalene".
    classify_triangle(2, 2, 3) -> "isosceles"    classify_triangle(1, 2, 3) -> "invalid"
Solve “Triangle Type” in your browser →

4. Largest of Three WITHOUT max() — nested / combined if

Easy2 ways to solve
📤 OUTPUT: return an int, e.g. 9. Use `return`, not print().
    max_of_three(3, 9, 4) -> 9
Ways: if a >= b and a >= c ...  ·  keep a running `best` variable
Solve “Largest of Three WITHOUT max() — nested / combined if” in your browser →

5. Cinema Ticket Pricing — order of conditions

Medium1 way to solve
📤 OUTPUT: return an int, e.g. 120. Use `return`, not print().
Real world rules (check in this priority):
    age < 0          -> -1 (invalid)
    age < 5          -> 0 (free)
    age >= 60        -> 150 (senior)
    is_student       -> 120
    age < 18         -> 100 (child)
    otherwise        -> 200
    ticket_price(16, True) -> 120    ticket_price(65, True) -> 150   ticket_price(3, False) -> 0
Solve “Cinema Ticket Pricing — order of conditions” in your browser →

6. Which Quadrant? — nested conditions

Easy2 ways to solve
📤 OUTPUT: return a str (text), e.g. 'Q4'. Use `return`, not print().
Return "origin", "x-axis", "y-axis", "Q1", "Q2", "Q3" or "Q4".
    quadrant(3, -2) -> "Q4"     quadrant(0, 5) -> "y-axis"
Solve “Which Quadrant? — nested conditions” in your browser →

7. Courier Shipping — nested if + ternary

Medium2 ways to solve
📤 OUTPUT: return an int, e.g. 50. Use `return`, not print().
Base: weight <= 1 kg -> 50, <= 5 kg -> 100, else 100 + 20 per kg ABOVE 5 (partial kg counts as full).
distance_km > 500 adds 50%.  express doubles the final price.  Return an int (use int() at the end).
    shipping_cost(0.5, False, 100) -> 50
    shipping_cost(6.2, False, 100) -> 140      (100 + 2 extra kg * 20)
    shipping_cost(2, True, 800)    -> 300      (100 * 1.5 * 2)
Solve “Courier Shipping — nested if + ternary” in your browser →

8. Ride-Hailing Surge Pricing — interview at a ride-hailing company

Project1 way to solve
📤 OUTPUT: return a tuple (fare, surge), e.g. (288.0, 1.2). Use `return`, not print().
Interviewer: "Price a ride. When demand is high, surge kicks in."
fare = base + per_km * km + per_min * minutes        (numbers from VEHICLES above)
surge: demand_ratio <= 1 -> 1.0;  <= 1.5 -> 1.2;  <= 2 -> 1.5;  above 2 -> 2.0
fare = max(fare * surge, minimum fare), rounded to 2.
Unknown vehicle -> raise ValueError("unknown vehicle").    Return (fare, surge)
    ride_fare(10, 25, 1.3, "cab") -> (288.0, 1.2)
Solve “Ride-Hailing Surge Pricing — interview at a ride-hailing company” in your browser →

9. Stage 5 — Token Classifier (a long if/elif chain, like every real lexer has)

Compiler1 way to solve
📤 OUTPUT: return a str (text), e.g. 'NUMBER'. Use `return`, not print().
Return "NUMBER" (digits with at most one ".", at least one digit), "STRING" (starts AND ends with ",
length >= 2), "KEYWORD" (in KEYWORDS), "IDENT" (valid identifier, not a keyword),
"OP" (in OPERATORS), "LPAREN" for "(", "RPAREN" for ")", otherwise "UNKNOWN".
Solve “Stage 5 — Token Classifier (a long if/elif chain, like every real lexer has)” in your browser →

← Operators & operator precedence Loops, nested loops, break / continue →