Chapter 2 — Control Flow: Conditions & Loops
Table of Contents
- Truthiness & Comparisons
- if / elif / else (+ nested)
- Conditional Expression (Ternary)
- match–case (Python 3.10+)
- Loops Overview
- while Loop
- for Loop & range()
- Loop
else - break, continue, pass
- enumerate() & zip()
- Nested Loops & Pattern Programs
- Input Validation Patterns
- Mini Programs (5)
- Practice Questions (10)
- Quick Cheatsheet
1) Truthiness & Comparisons
What: Python me kuch values “falsy” hoti hain:
0, 0.0, "", [], {}, set(), None. Baaki sab truthy.Why: Conditions likhte time direct value check kar sakte ho; clean code.
if "BeSmart":
print("truthy")
if []:
print("won't run")
# comparisons: ==, !=, <, >, <=, >= ; chained:
x = 3
print(1 < x < 5) # True
2) if / elif / else (+ nested)
What: Condition true ho to block execute.
Why: Program decisions & branching implement karne ka base.
marks = float(input("Percent: "))
if marks >= 90:
grade = "A+"
elif marks >= 75:
grade = "A"
elif marks >= 60:
grade = "B"
else:
grade = "C"
print("Grade:", grade)
Nested example
age = int(input("Age: "))
if age >= 18:
id_proof = input("Do you have ID? (y/n): ").lower()
if id_proof == "y":
print("Allowed")
else:
print("Bring ID")
else:
print("Not allowed")
3) Conditional Expression (Ternary)
What: One-line if-else:
X if cond else Y.Why: Short, readable assignments.
n = int(input("Number: "))
parity = "even" if n % 2 == 0 else "odd"
print(parity)
4) match–case (Python 3.10+)
What: Switch-style matching; patterns bhi support.
Why: Multiple choices ko clean tareeke se handle.
day = input("Day (mon/tue/...): ").lower()
match day:
case "mon" | "tue" | "wed" | "thu" | "fri":
print("Weekday")
case "sat" | "sun":
print("Weekend")
case _:
print("Unknown")
5) Loops Overview
What:
while (condition-based), for (iterate over sequence/iterable).Why: Repetition/automation, collections traversal, calculations.
6) while Loop
What: Jab tak condition True, tab tak run.
Why: Unknown iterations (sentinel input, waiting, retries).
# Sum of positive numbers until user enters 0
total = 0
n = int(input("Enter number (0 to stop): "))
while n != 0:
if n > 0:
total += n
n = int(input("Enter number (0 to stop): "))
print("Total:", total)
7) for Loop & range()
What:
range(stop), range(start, stop[, step]).Why: Counted loops; indexes; stepping; reverse.
# Multiplication table
n = int(input("Table of: "))
for i in range(1, 11):
print(f"{n} x {i} = {n*i}")
# Reverse loop
for i in range(5, 0, -1):
print(i, end=" ") # 5 4 3 2 1
8) Loop else
What:
for/while ke baad else tab chalti hai jab loop break se exit na ho.Why: “Found / Not found” patterns me useful.
# Prime check using for-else
n = int(input("Enter number: "))
if n < 2:
print("Not prime")
else:
for d in range(2, int(n**0.5)+1):
if n % d == 0:
print("Not prime"); break
else:
print("Prime")
9) break, continue, pass
break: loop se turant bahar niklo
continue: current iteration skip
pass: placeholder (do nothing)
continue: current iteration skip
pass: placeholder (do nothing)
# find first multiple of 7 between 1..100
for i in range(1, 101):
if i % 7 == 0:
print("Found:", i)
break
# print 1..10 except multiples of 3
for i in range(1, 11):
if i % 3 == 0:
continue
print(i, end=" ")
# TODO placeholder
def feature():
pass
10) enumerate() & zip()
What:
enumerate(iterable, start=0) index+item; zip(a,b,...) parallel iterate.Why: Cleaner loops; manual index handling se better.
names = ["Riya", "Aarav", "Kabir"]
scores = [92, 88, 76]
for idx, (n, s) in enumerate(zip(names, scores), start=1):
print(idx, n, s)
11) Nested Loops & Pattern Programs
A) Right Triangle (stars)
rows = int(input("Rows: "))
for i in range(1, rows+1):
print("*" * i)
B) Pyramid (centered)
n = int(input("Rows: "))
for i in range(1, n+1):
spaces = " " * (n - i)
stars = "*" * (2*i - 1)
print(spaces + stars)
C) Number Triangle
n = int(input("Rows: "))
for i in range(1, n+1):
line = ""
for j in range(1, i+1):
line += str(j) + " "
print(line)
D) Inverted Triangle
n = int(input("Rows: "))
for i in range(n, 0, -1):
print("*" * i)
12) Input Validation Patterns
Tip: Loop me input lo jab tak valid na ho (e.g., positive number).
while True:
try:
x = int(input("Enter positive int: "))
if x > 0:
break
print("Must be > 0")
except ValueError:
print("Enter a valid integer")
print("OK:", x)
13) Mini Programs (5)
A) Simple Menu (while + match/if)
balance = 1000.0
while True:
print("\\n1) Check 2) Deposit 3) Withdraw 4) Exit")
ch = input("Choice: ")
if ch == "1":
print("Balance:", balance)
elif ch == "2":
amt = float(input("Amount: "))
if amt > 0: balance += amt
else: print("Invalid")
elif ch == "3":
amt = float(input("Amount: "))
if 0 <= amt <= balance: balance -= amt
else: print("Insufficient/Invalid")
elif ch == "4":
print("Bye"); break
else:
print("Invalid choice")
B) Guess the Number (1–100)
import random
target = random.randint(1, 100)
tries = 0
while True:
n = int(input("Guess (1-100): "))
tries += 1
if n == target:
print("Correct in", tries, "tries"); break
elif n < target:
print("Too low")
else:
print("Too high")
C) Factorial (for)
n = int(input("n: "))
fact = 1
for i in range(2, n+1):
fact *= i
print("Factorial:", fact)
D) GCD (Euclid, while)
a = int(input("a: ")); b = int(input("b: "))
while b != 0:
a, b = b, a % b
print("GCD:", a)
E) Armstrong Number (3-digit)
n = int(input("n (100..999): "))
s = sum(int(d)**3 for d in str(n))
print("Armstrong" if s == n else "Not Armstrong")
14) Practice Questions (Easy → Hard)
- Concept: Truthy vs Falsy values list karo; examples do.
- Code: Percent → Grade (A+/A/B/C) if/elif/else se likho (cutoffs aap choose karo).
- Ternary: Input number ki parity (even/odd) 1-line me print karo.
- match–case: Month number (1–12) → season print karo (3.10+).
- Loop: 1..N ka sum (while & for dono versions).
- Loop-else: List me target mila ya nahi — message print karo.
- break/continue: 1..50 me sirf multiples of 5 print karo; 25 ke baad stop.
- enumerate/zip: Do lists (subjects, marks) ko side-by-side index ke saath print karo.
- Patterns: User rows ke hisab se hollow square print karo.
- Challenge: Prime numbers between A..B print karo (efficient √n check), count bhi batao.
15) Quick Cheatsheet
Conditions:
if/elif/else; chained:1 < x < 5- Ternary:
X if cond else Y match-case(3.10+)
Loops:
while,for x in iterable,range()break,continue,pass- Loop
elseruns if nobreak enumerate(),zip()