ЁЯФм
ЁЯзм
ЁЯФн
ЁЯкР
ЁЯзк
тЖР Back to Dashboard
Font Size:

1. Introduction

By default, Python executes the statements of a program in the order they are written, one after another, from top to bottom. This is called sequential flow of control. Real-world problems, however, are rarely so linear: a program must take different actions depending on conditions, and it must often repeat a block of statements many times. Flow of control is the study of the statements that change this natural order: decision-making statements (if, if-else, if-elif-else) and iteration or looping statements (while, for).

The power of a computer lies precisely in its ability to make decisions and repeat tasks millions of times without fatigue. A single program can check whether a student has passed, loop over a list of a hundred marks to compute the average, or keep asking for valid input until the user enters it correctly. All of this is accomplished with the control statements introduced in this chapter.

This chapter explains the three types of flow: sequential, selective (decision) and iterative (repetitive). It covers the if family of statements, the while and for loops, the break, continue and else clauses, nested loops, and the range() function. Mastering flow of control is the key to writing programs that can solve meaningful, non-trivial problems, and it prepares the student for the collection types of the later chapters.

2. Sequential Flow

In sequential flow, statements are executed in the exact order in which they appear, top to bottom, with no jumping and no repetition. Almost every program starts with a sequential section, for example reading inputs and printing a first result.

x = 5
y = 10
z = x + y
print(z)

Here the statements run strictly in order: x gets 5, y gets 10, z gets the sum, and 15 is printed. Only when we introduce conditions and loops does the flow become non-sequential.

3. Decision Making (Selection)

Python provides the if statement, the if-else statement and the if-elif-else chain for making decisions. The condition of an if statement is a Boolean expression; if it evaluates to True, the indented block that follows is executed, otherwise it is skipped.

3.1 The if Statement

age = 17
if age >= 18:
    print("You are eligible to vote")
print("End of program")

Since 17 is not greater than or equal to 18, the message inside the if block is not printed, but the last print statement always runs.

3.2 The if-else Statement

The else clause provides an alternative block that executes when the condition is False.

number = 7
if number % 2 == 0:
    print("Even number")
else:
    print("Odd number")

3.3 The if-elif-else Chain

When more than two alternatives exist, the elif (else-if) clause is used. Python checks the conditions in order and executes the block of the first true condition.

marks = 82
if marks >= 90:
    grade = "A"
elif marks >= 75:
    grade = "B"
elif marks >= 60:
    grade = "C"
else:
    grade = "D"
print("Grade:", grade)

For marks 82, the first condition fails, the second succeeds, and grade becomes "B". Only one block ever executes in an if-elif-else chain.

3.4 Nested if Statements

An if statement can be placed inside another if statement. This is called nesting and is used when a decision depends on another decision.

n = 15
if n > 0:
    if n % 2 == 0:
        print("Positive even")
    else:
        print("Positive odd")
else:
    print("Non-positive")

4. Iteration: Loops

Loops allow a block of statements to be executed repeatedly. Python has two loop statements: while and for.

4.1 The while Loop

The while loop repeats its body as long as its condition evaluates to True. The condition is checked before each iteration, so if it is False initially, the body never executes. It is essential that the loop body eventually makes the condition False, otherwise the loop runs forever (infinite loop).

count = 1
while count <= 5:
    print("Iteration", count)
    count += 1

This prints Iteration 1 through 5. The statement count += 1 is the loop control variable update that guarantees termination.

4.2 The for Loop with range()

The for loop iterates over a sequence. The most common use is with the range() function, which generates a sequence of numbers.

for i in range(5):
    print(i)          # prints 0 1 2 3 4

range(stop) generates 0 to stop-1. range(start, stop) generates start to stop-1. range(start, stop, step) adds a step value.

for i in range(2, 10, 2):
    print(i)          # prints 2 4 6 8

4.3 for Loop over a Sequence

The for loop can also iterate directly over any sequence, such as a string or list.

for ch in "Python":
    print(ch, end=" ")   # P y t h o n

for num in [10, 20, 30]:
    print(num)           # 10 20 30

5. The range() Function

range() is a built-in function that returns a sequence of numbers. It is used extensively with for loops.

The end value is always exclusive, the start value is inclusive, and the step can be negative to count backwards.

6. The break and continue Statements

The break and continue statements alter the normal flow of a loop.

for i in range(1, 10):
    if i == 5:
        break
    print(i)        # prints 1 2 3 4, then stops

for i in range(1, 6):
    if i == 3:
        continue
    print(i)        # prints 1 2 4 5 (3 is skipped)

7. The else Clause with Loops

In Python, loops can have an optional else clause. The else block executes only when the loop finishes normally without hitting a break. If the loop is terminated by break, the else block is skipped. This is a distinctive Python feature.

for i in range(1, 8):
    if i % 4 == 0:
        print("Found", i)
        break
else:
    print("No multiple of 4 found")

Since 4 is found and break executes, the else block does not run.

8. Nested Loops

A loop inside another loop is called a nested loop. For each iteration of the outer loop, the entire inner loop runs completely. Nested loops are used for problems involving rows and columns, such as printing patterns.

for i in range(1, 4):
    for j in range(1, 4):
        print(i * j, end=" ")
    print()

This prints a 3 x 3 multiplication table: 1 2 3 2 4 6 3 6 9

9. Sample Programs Using Flow of Control

9.1 Print Numbers Divisible by 3

for num in range(1, 30):
    if num % 3 == 0:
        print(num, end=" ")

9.2 Sum of Natural Numbers

n = int(input("Enter n: "))
total = 0
i = 1
while i <= n:
    total += i
    i += 1
print("Sum =", total)

9.3 Count Vowels in a Word

word = input("Enter a word: ").lower()
count = 0
for ch in word:
    if ch in "aeiou":
        count += 1
print("Vowel count:", count)

Quick Revision Tables

Table 1: if Statement Family

Statement Use
if Execute block if condition is True
if-else Execute one of two blocks
if-elif-else Execute one of many blocks
Nested if An if inside an if for dependent conditions

Table 2: range() Forms

Call Sequence Generated
range(5) 0, 1, 2, 3, 4
range(2, 6) 2, 3, 4, 5
range(1, 10, 2) 1, 3, 5, 7, 9
range(5, 0, -1) 5, 4, 3, 2, 1

Mind Map

flowchart TD A[Flow of Control] --> B[Sequential] A --> C[Selection] C --> C1[if] C --> C2[if-else] C --> C3[if-elif-else] C --> C4[Nested if] A --> D[Iteration] D --> D1[while loop] D --> D2[for loop] D --> D3[range function] D --> D4[Nested loops] A --> E[Loop Control] E --> E1[break] E --> E2[continue] E --> E3[else with loop]

Important Diagrams (SVG)

Diagram 1: if-elif-else Decision Flow

Decision Making in Python marks >= 90? Grade = A marks >= 75? Grade = B else Grade = D Only one branch executes. Conditions are checked top to bottom. Golden Rule: In if-elif-else, exactly one block runs, based on the first condition that is True.

Diagram 2: Flow of while Loop

Working of a while Loop START count = 1 count <= 5? Loop Body print + count += 1 Exit Loop Condition False -> exit count += 1 eventually makes the condition False, preventing an infinite loop. Golden Rule: A while loop repeats while its condition is True; update the control variable to avoid infinite loops.

Common Mistakes

  1. Creating infinite loops: Forgetting to update the loop control variable inside a while loop causes the program to run forever.
  2. Using = instead of == in conditions: if x = 5 is a syntax error and if x == 5 is the correct comparison.
  3. Off-by-one errors with range: range(5) gives 0 to 4, not 1 to 5. Remember the end value is exclusive.
  4. Misplacing the else of an if: Indentation decides which block belongs to which condition; wrong indentation changes program logic.
  5. Putting the condition for break in the wrong place: break should be checked inside the loop where the exit condition is detected.
  6. Forgetting that continue skips the rest of the iteration: Statements after continue in the same block never run for that iteration.
  7. Writing an infinite loop unintentionally with while True: Unless a break exits it, the program never terminates.
  8. Wrong order in if-elif-else: Putting a general condition (like >= 60) before a specific one (like >= 90) makes the specific branch unreachable.

Exam Tips

  1. Practise dry runs: trace loops on paper with a small value (like count <= 5) to record each output; this is the best way to avoid errors.
  2. Memorise the exact outputs of range() forms, particularly that the stop value is exclusive.
  3. Know the difference between break and continue with one line each: break ends the loop, continue skips one iteration.
  4. Remember the special Python feature of else with loops; it executes only when the loop finishes without break.
  5. Be able to write pattern programs with nested loops (like a multiplication table), a frequent long-answer question.
  6. For while loop questions, always identify the initial value, the condition, and the update statement.
  7. Use proper indentation in programming questions; in Python indentation is part of the syntax.

Conclusion

Flow of control gives programs the ability to make choices and repeat work, transforming them from linear sequences into powerful decision-making machines. Sequential execution is the default, but the if family of statements provides selection, while and for loops provide iteration, and break, continue and the loop-else clause fine-tune the flow. The range() function makes numeric loops simple, and nested loops handle two-dimensional problems like tables and patterns. These control structures are the backbone of every meaningful program. In the next chapter, we apply these skills to strings, one of the most widely used data types, learning to process text character by character.