BCC302 · Python Programming · Unit 2
Python Program Flow Control Conditional blocks
Unit Scope & Exam Weightage: This unit controls the order of execution: if / elif / else decisions, for and while iteration with range(), iteration over strings, lists and dictionaries, and the loop-control statements pass, continue, break and loop-else. The supplied question set contains 18 recorded clusters; 7-mark questions are strongly program-oriented — multiplication tables, patterns, LCM, prime numbers, password validation and grade calculation.
Front Page: Importance-Wise Topic Roadmap (2023–26 PYQs)
| Priority | Topic (Exact Syllabus) | PYQs Asked | Marks Weightage | Tag |
|---|---|---|---|---|
| 1 | Programming using Python conditional and loop blocks | 8 (2023-24 ×3, 2024-25 ×2, 2025-26 ×3) |
7m ×8 | Survival Mode |
| 2 | Use of while loops in python; Simple for loops in python | 5 (2023-24 ×3, 2024-25, 2025-26) |
2m + 7m ×4 | Core Concept |
| 3 | if; else and else if | 4 (2024-25, 2025-26 ×3) |
2m + 7m ×3 | Decision Tables |
| 4 | Loop manipulation using pass; continue; break and else | 4 (2023-24, 2024-25, 2025-26 ×2) |
2m + 7m ×3 | Tricky Syntax |
| 5 | string; list and dictionaries (iteration) | 3 (2024-25, 2025-26 ×2) |
7m ×3 | Data Iteration |
| 6 | For loop using ranges | Integrated in #1–#2 | — | Worked Examples |
2-Hour Last-Night Survival Checklist:
- Loop choice (Priority 2): Use
forwhen the number of iterations is known (range(n)),whilewhen it depends on a condition. - Range (Priority 6):
range(stop)→ 0…stop−1;range(start, stop, step)excludes stop;range(1,10,2) → 1,3,5,7,9. - Loop control (Priority 4):
breakexits,continueskips the rest of this iteration,passdoes nothing,elseruns only when the loop finished without break. - Pattern programs: practise the triangle, hollow pyramid and multiplication table using nested
forloops; keep the exact spacing logic in mind. - Password validator: memorise the six criteria and write them with
any(),len()and a comma-separated input split.
1. Conditional Blocks: if, else, elif
Conditional statement: A control structure that executes a block only when a Boolean condition is true. Python uses if, zero or more elif (else-if) branches, and an optional final else.
if condition1:
statement(s) # runs when condition1 is True
elif condition2:
statement(s) # checked only if condition1 was False
else:
statement(s) # runs when none of the above matched
Key rules: conditions need not be parenthesised but must evaluate to bool; every branch ends with a colon; only one branch executes; elif is checked top-down so put the most specific case first.
1.1 Worked Example — Positive, Negative or Zero
n = int(input("Enter a number: "))
if n > 0:
print("Positive")
elif n < 0:
print("Negative")
else:
print("Zero")
Flow diagram:
%%{init: {'theme': 'base', 'look': 'handDrawn', 'themeVariables': {'fontFamily': "'Nunito', sans-serif", 'fontSize': '17px', 'primaryColor': '#EFEAD6', 'primaryBorderColor': '#0F766E', 'lineColor': '#23211C'}}}%%
flowchart TD
S["Read n"] --> Q1{"n > 0 ?"}
Q1 -->|Yes| P["Print Positive"]
Q1 -->|No| Q2{"n < 0 ?"}
Q2 -->|Yes| N["Print Negative"]
Q2 -->|No| Z["Print Zero"]
Python Examiner Tip: In an elif chain, changing the order can change the answer. For grade programs, test the highest range first (marks >= 90) or a lower condition will swallow it.
After-Topic PYQs:
- 2025-26 (Sec A, 2 Marks): "Explain the use of if, else, and elif. Write a Python program to check the given number is even or odd using if and else statement."
- 2025-26 (Sec C, 7 Marks): "What are conditional statements in Python? Explain if, else, and elif with examples."
- 2025-26 (Sec C, 7 Marks): "Write a Python program to check whether a number is positive, negative, or zero using conditional blocks."
- 2025-26 (Sec C, 7 Marks): "Explain Python blocks and conditional statements. Write a program to grade students based on marks using elif."
2. for Loops and range()
for loop: A definite iteration structure that visits each item of a sequence (string, list, tuple, dict, set) or the integers produced by range().
for variable in sequence:
statement(s)
2.1 range() Forms (Asked Frequently)
| Call | Produces | Use |
|---|---|---|
range(5) |
0 1 2 3 4 |
repeat 5 times |
range(2, 6) |
2 3 4 5 |
start inclusive, stop exclusive |
range(1, 10, 2) |
1 3 5 7 9 |
step of 2 |
range(10, 0, -1) |
10 … 1 |
countdown |
len(range(2,6)) |
4 |
count of values |
2.2 Iterating Strings, Lists and Dictionaries
for ch in "Python": # characters one by one
print(ch, end=" ")
marks = [88, 72, 95]
for m in marks: # list elements
print(m + 5)
student = {"roll": 21, "name": "Asha"}
for key in student: # keys by default
print(key, student[key])
for k, v in student.items(): # pairs
print(k, v)
2.3 Nested Loops and Patterns
A loop inside another loop is a nested loop; the inner loop completes fully for each outer iteration. It is used for tables, matrices and star patterns.
n = 5
for i in range(1, n + 1): # rows
for j in range(1, i + 1): # columns grow with row
print("*", end="")
print() # new line after each row
Output is a right-angled triangle of * with 1 to 5 stars per row. For a hollow pyramid, print stars only at the two ends of each row and a full star row at the bottom.
After-Topic PYQs:
- 2023-24, 2025-26 (Sec C, 7 Marks): "Explain for and while loops used in Python with appropriate example."
- 2025-26 (Sec C, 7 Marks): "Discuss for loops with strings and lists. Write a program to sum elements of a list."
- 2024-25 (Sec C, 7 Marks): "Discuss the use of nested loops in Python. Write a program to print a right-angled triangle of stars."
- 2024-25 (Sec C, 7 Marks): "Write a Python program using for loop and dictionary to display student grades."
- 2025-26 (Sec C, 7 Marks): "Write a Python program using conditional statements and loops to print the multiplication table of a number."
3. while Loops
while loop: An indefinite iteration structure that repeats a block while a condition remains true. The condition must be changed inside the loop, or the loop never ends.
i = 1
while i <= 5:
print(i)
i += 1 # update is mandatory
| Feature | for |
while |
|---|---|---|
| Iteration count | Known in advance | Unknown; decided by condition |
| Sequence | Iterates over items | No sequence needed |
| Update step | Automatic | Programmer must update |
| Risk | Rare infinite loop | Infinite loop if condition never becomes false |
| Example | for i in range(10) |
while balance > 0 |
After-Topic PYQs:
- 2024-25 (Sec A, 2 Marks): "Differentiate between for loop and while loop with syntax and examples."
- 2023-24 (Sec B, 7 Marks): "Explore the working of while, and for loop with examples."
- 2024-25 (Sec C, 7 Marks): "Explain why loops are needed and the types of loops in python. Discuss break and continue with example."
4. Loop Manipulation: pass, continue, break, else
Loop manipulation statements alter the normal flow inside a loop: break terminates the loop, continue jumps to the next iteration, pass is a null statement, and the loop's else runs after normal completion.
| Statement | Effect | Typical Use |
|---|---|---|
break |
Exits the nearest enclosing loop immediately | Stop when a match is found |
continue |
Skips remaining statements of this iteration | Ignore unwanted items |
pass |
Does nothing; placeholder | Empty function/loop body to be filled later |
else with loop |
Runs when the loop ends without break |
Search-found detection |
4.1 The Loop-else Rule (2-Mark Favourite)
for n in range(2, 10):
if n % 7 == 0:
print("Found", n)
break
else:
print("No multiple of 7") # NOT printed because break occurred
If the loop finishes all iterations without break, the else executes; if break ran, it is skipped. The same rule applies to while ... else.
4.2 Prime Numbers 1–50 (Using for ... else)
for n in range(2, 51):
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0:
break
else:
print(n, end=" ")
Why it works: if no divisor is found, the inner loop completes without break, so its else prints the prime. Checking up to √n is sufficient.
After-Topic PYQs:
- 2023-24 (Sec A, 2 Marks): "Can you use else with a for loop? If so, when is it executed?"
- 2025-26 (Sec C, 7 Marks): "Describe loop manipulation statements: pass, continue, break. Write a program to print prime numbers between 1 to 50 using for loop."
- 2025-26 (Sec C, 7 Marks): "What are break, continue, and pass statements? Give code examples."
- 2024-25 (Sec C, 7 Marks): "What are break, continue, and pass statements? Give code examples."
Solved Exam-Ready Questions
Solved Q1 (2023-24, 2025-26 Sec C — 7 Marks | Survival Mode)
Q: Explain for and while loops used in Python with appropriate example.
Solution:
for: definite iteration over a sequence orrange; syntaxfor x in seq:. Examplefor i in range(1, 6): print(i)→ 1 2 3 4 5.range(start, stop, step)excludes stop. It can iterate strings (for ch in "Python"), lists and dictionary keys/items.while: repeats while a condition is true; syntaxwhile cond:, with a mandatory update. Examplei=1; while i<=5: print(i); i+=1.- Comparison table: known vs unknown count, automatic vs manual update, sequence vs condition, infinite-loop risk.
elseclause: both loops supportelse, executed only when nobreakoccurred.- Conclusion: choose
forfor counted tasks (tables, list sums) andwhilefor condition-driven tasks (menu until quit).
Solved Q2 (2025-26 Sec C — 7 Marks)
Q: What are conditional statements in Python? Explain if, else, and elif with examples.
Solution:
- Concept: Conditional statements choose a branch using a Boolean expression; Python uses colon + indentation.
if:if age >= 18: print("Adult")— the block runs only if true.if ... else: two-way choice —if marks >= 40: print("Pass") else: print("Fail").elif: multi-way choice — grade example:
m = int(input("Marks: "))
if m >= 90: g = "A+"
elif m >= 80: g = "A"
elif m >= 60: g = "B"
elif m >= 40: g = "C"
else: g = "F"
print("Grade:", g)
- Rules: conditions evaluated top-down, only one branch runs, put the strictest condition first.
- Conclusion: conditionals give programs decision-making ability; combined with loops they implement all algorithms.
Solved Q3 (2025-26 Sec C — 7 Marks)
Q: Write a Python program to check whether a number is positive, negative, or zero using conditional blocks.
Solution:
n = int(input("Enter a number: "))
if n > 0:
print("Positive")
elif n < 0:
print("Negative")
else:
print("Zero")
Step-by-step: input() returns a string → int() converts it → first condition tests n > 0; if false, elif n < 0; if both false, n must be zero → else. Test cases: 12 → Positive, −4 → Negative, 0 → Zero. The mutually exclusive branches guarantee exactly one output.
Solved Q4 (2023-24 Sec C — 7 Marks)
Q: Write a Python Program to find the LCM of two numbers.
Solution:
a = int(input("First number: "))
b = int(input("Second number: "))
if a > b:
bigger, smaller = a, b
else:
bigger, smaller = b, a
lcm = bigger
while lcm % smaller != 0:
lcm += bigger
print("LCM:", lcm)
Reasoning: the LCM must be a multiple of the larger number; start there and keep adding the larger number until the value is also divisible by the smaller. For 12 and 18: start 18 → 36 is divisible by 12 → answer 36. Alternative one-liner uses abs(a*b)//math.gcd(a,b) after importing math.
Solved Q5 (2023-24 Sec C — 7 Marks)
Q: *A website requires the users to input username and password to register. Construct a program to check the validity of password input by users. Following are the criteria for checking the password:
- At least 1 letter between [a-z]
- At least 1 number between [0-9]
- At least 1 letter between [A-Z]
- At least 1 character from [$#@]
- Minimum length of transaction password: 6
- Maximum length of transaction password: 12 Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma*
Solution:
s = input("Enter comma separated passwords: ")
passwords = [p.strip() for p in s.split(",")]
valid = []
for p in passwords:
ok = (6 <= len(p) <= 12
and any('a' <= c <= 'z' for c in p)
and any('A' <= c <= 'Z' for c in p)
and any('0' <= c <= '9' for c in p)
and any(c in "$#@" for c in p))
if ok:
valid.append(p)
print(",".join(valid))
Explanation: split the input on commas and strip spaces; any() checks each of the four character-class conditions; the length is bounded by 6 and 12; only passwords satisfying all six criteria are appended; ",".join() prints them comma-separated. Sample: input AB1$d,abc,p@ssW1 → output AB1$d,p@ssW1.
Solved Q6 (2025-26 Sec C — 7 Marks)
Q: Describe loop manipulation statements: pass, continue, break. Write a program to print prime numbers between 1 to 50 using for loop.
Solution:
pass: null statement used where syntax requires a body but no action is needed, e.g.if x > 0: pass.continue: skips the remaining statements in the current iteration and jumps to the next iteration, e.g. skip negatives withif n < 0: continue.break: exits the loop immediately, e.g. stop searching once found.- Program:
for n in range(2, 51):
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0:
break
else:
print(n, end=" ")
- Trace: for
n=9,d=3divides 9 →break→ innerelseskipped, so 9 is not printed. Forn=7, no divisor → innerelseprints 7.
Solved Q7 (2024-25 Sec C — 7 Marks)
Q: *Write a program to create a hollow pyramid pattern given below: *
- *
-
-
*
Solution:
n = 5
for i in range(1, n + 1):
stars = "*" * (2 * i - 1) # full row width
if i == 1 or i == n: # top and bottom are solid
print(stars)
else:
print("*" + " " * (len(stars) - 2) + "*")
Explanation: row i has width 2i−1. The first row (i=1) and last row (i=n) are printed solid; intermediate rows print one star, then width−2 spaces, then one star. Sample output matches the given pattern for n=5. Nested loops can be used instead of string repetition:
for i in range(1, 6):
for j in range(1, 2*i):
if j == 1 or j == 2*i-1 or i == 5:
print("*", end="")
else:
print(" ", end="")
print()
Solved Q8 (2025-26 Sec C — 7 Marks)
Q: Write a Python program using for loop and dictionary to display student grades.
Solution:
students = {"Asha": 88, "Ravi": 72, "Meera": 95, "Karan": 39}
for name, marks in students.items():
if marks >= 90:
grade = "A+"
elif marks >= 80:
grade = "A"
elif marks >= 60:
grade = "B"
elif marks >= 40:
grade = "C"
else:
grade = "F"
print(name, marks, grade)
Explanation: students.items() yields (key, value) pairs; the if/elif chain assigns a grade; print displays all three values. Sample output: Asha 88 A, Ravi 72 B, Meera 95 A+, Karan 39 F.
Practice Questions (Self-Test)
- (2 Marks) What does
range(2, 10, 3)produce? (Ans: 2, 5, 8) - (2 Marks) When does a
for ... elseblock execute? - (7 Marks) Write a program to print the multiplication table of 7 using a
forloop. - (7 Marks) Write a program to sum the elements of a list using a
forloop. - (7 Marks) Write a program to print primes from 1 to 50 using
continueinstead offor ... else. - (7 Marks) Write a program to check a password against six validity criteria using
any(). - (7 Marks) Explain nested loops with a program that prints a 5-row right-angled triangle of stars.