MODULE 02

Control Flow

Detailed step-by-step learning of conditions, if/elif/else, nested conditions, for loops, while loops, range(), break, continue, pass, nested loops and practical programming patterns.

10+Core Topics
20+Subtopics
30Coding Questions
30Theory Q&A

Module Contents

1. Conditions and Decision Making

1.1 What is control flow?

Control flow is the order in which Python executes statements. Normally code runs from top to bottom. Conditions select a path and loops repeat a path.

print("Step 1")
print("Step 2")
print("Step 3")

1.2 Why are conditions required?

Programs need to make decisions such as pass/fail, login success, discount eligibility, age verification and stock availability.

  • If marks are 40 or above → pass.
  • If age is 18 or above → eligible.
  • If stock is 0 → unavailable.

1.3 Boolean conditions

age = 20
print(age >= 18)

The result is True. Common comparison operators are ==, !=, >, <, >=, and <=.

1.4 Logical operators

OperatorMeaningExample
andBoth conditions Trueage >= 18 and has_id
orAt least one Truecash > 0 or card
notReverses resultnot closed
age = 25
has_id = True
if age >= 18 and has_id:
    print("Entry allowed")

1.5 Writing complex conditions

if (age >= 18 and has_id) or is_admin:
    print("Allowed")
Tip: Write the decision in plain English first, then translate it into Python.

2. if, elif and else

2.1 if statement

age = 21
if age >= 18:
    print("Adult")

Step-by-step

  1. Store 21 in age.
  2. Evaluate age >= 18.
  3. The result is True.
  4. Enter the indented block.
  5. Print Adult.

2.2 Indentation

Indentation defines which statements belong to a condition.

marks = 75
if marks >= 40:
    print("Pass")
    print("Good job")
print("Program finished")

2.3 if...else

marks = 32
if marks >= 40:
    print("Pass")
else:
    print("Fail")

Exactly one branch executes.

2.4 if...elif...else

marks = 82
if marks >= 90:
    grade = "A+"
elif marks >= 75:
    grade = "A"
elif marks >= 60:
    grade = "B"
elif marks >= 40:
    grade = "C"
else:
    grade = "Fail"
print(grade)
Important: Python checks conditions from top to bottom and executes the first matching branch.

2.5 Conditional expression

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

3. Nested Conditions

3.1 What is a nested if?

A nested condition is an if statement inside another conditional block.

age = 22
has_id = True
if age >= 18:
    if has_id:
        print("Entry allowed")
    else:
        print("ID required")
else:
    print("Underage")
  1. Check age.
  2. Only if age is valid, check the ID.
  3. Select the appropriate inner branch.

3.2 Practical example

marks = 85
attendance = 90
if marks >= 40:
    if attendance >= 75:
        print("Eligible")
    else:
        print("Low attendance")
else:
    print("Failed")
Common mistake: Too many nested levels can make code difficult to read. Simplify related checks when practical.

4. for Loop

4.1 What is a for loop?

A for loop visits each item in an iterable such as a string, list, tuple, set, dictionary or range.

for i in range(5):
    print(i)

Output: 0, 1, 2, 3, 4.

4.2 Step-by-step execution

  1. range(5) represents 0 through 4.
  2. Python assigns the next value to i.
  3. The indented block runs.
  4. The next value is assigned.
  5. The loop stops after the final value.

4.3 Loop through a string

name = "Python"
for ch in name:
    print(ch)

4.4 Loop through a list

fruits = ["Apple", "Banana", "Mango"]
for fruit in fruits:
    print(fruit)

4.5 for with condition

for number in range(1, 11):
    if number % 2 == 0:
        print(number)

4.6 Accumulator pattern

total = 0
for number in range(1, 6):
    total += number
print(total)

The running total becomes 1 → 3 → 6 → 10 → 15.

5. while Loop

5.1 What is a while loop?

A while loop repeats while its condition is True.

count = 1
while count <= 5:
    print(count)
    count += 1

5.2 Step-by-step

  1. Set the starting value.
  2. Check the condition.
  3. Execute the body if True.
  4. Update the controlling variable.
  5. Repeat until the condition becomes False.

5.3 Infinite loops

# Intentional infinite loop example:
# while True:
#     print("Running")
A normal while loop should have a reliable exit condition or deliberate break.

5.4 When to use while?

Use it when repetition depends on a condition and the number of repetitions may not be known beforehand.

password = ""
while password != "python123":
    password = input("Enter password: ")
print("Access granted")

6. range() Function

6.1 range(stop)

for i in range(5):
    print(i)

Values: 0, 1, 2, 3, 4. Stop is excluded.

6.2 range(start, stop)

for i in range(2, 7):
    print(i)

Values: 2, 3, 4, 5, 6.

6.3 range(start, stop, step)

for i in range(2, 11, 2):
    print(i)

Values: 2, 4, 6, 8, 10.

6.4 Reverse range

for i in range(10, 0, -1):
    print(i)

The negative step moves backwards.

Remember: The stop value is never included in range().

7. Looping Through Data

7.1 Strings

word = "HELLO"
for ch in word:
    print(ch)

7.2 Lists

numbers = [10, 20, 30]
for n in numbers:
    print(n * 2)

7.3 Dictionary keys

student = {"name": "Ravi", "age": 21}
for key in student:
    print(key)

7.4 Dictionary keys and values

student = {"name": "Ravi", "age": 21}
for key, value in student.items():
    print(key, value)

7.5 enumerate()

names = ["A", "B", "C"]
for index, name in enumerate(names):
    print(index, name)

enumerate() is useful when you need both index and value.

8. break, continue and pass

8.1 break

break immediately exits the nearest loop.

for i in range(1, 11):
    if i == 6:
        break
    print(i)

Only 1 through 5 are printed.

8.2 continue

continue skips the remaining statements in the current iteration.

for i in range(1, 6):
    if i == 3:
        continue
    print(i)

Output: 1, 2, 4, 5.

8.3 pass

pass performs no operation. It is commonly used as a placeholder.

for i in range(1, 6):
    if i == 3:
        pass
    print(i)

3 is still printed.

StatementEffect
breakStops the loop
continueSkips current iteration
passDoes nothing

9. Nested Loops

9.1 What is a nested loop?

A loop inside another loop is called a nested loop. For every outer iteration, the inner loop normally completes its iterations.

for i in range(1, 4):
    for j in range(1, 4):
        print(i, j)

9.2 Multiplication table

n = 5
for i in range(1, 11):
    print(n, "x", i, "=", n*i)

9.3 Star pattern

for row in range(1, 6):
    for col in range(row):
        print("*", end=" ")
    print()
Dry-run tip: Track the outer variable and inner variable separately.

10. Practical Control-Flow Patterns

10.1 Find first match

numbers = [4, 8, 15, 20, 25]
for n in numbers:
    if n % 5 == 0:
        print(n)
        break

10.2 Count matches

numbers = [2, 4, 7, 8, 10]
count = 0
for n in numbers:
    if n % 2 == 0:
        count += 1
print(count)

10.3 Sum values

numbers = [10, 20, 30]
total = 0
for n in numbers:
    total += n
print(total)

10.4 Dry-run technique

For difficult loops, create a table containing iteration number, variable values, condition result and output. This makes execution easier to understand.

Iterationitotal
111
223
336
4410
Rule: Before writing a loop, identify the starting value, condition, update and stopping point.

11. 30 Coding Questions with Step-by-Step Solutions

Click a question to show the solution.

12. 30 Theory Questions with Answers

Useful for revision, interviews and classroom practice.