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.
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.
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.
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.
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")
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.
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")
Loops allow a block of statements to be executed repeatedly. Python has two loop statements: while and for.
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.
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
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
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.
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)
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.
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
for num in range(1, 30):
if num % 3 == 0:
print(num, end=" ")
n = int(input("Enter n: "))
total = 0
i = 1
while i <= n:
total += i
i += 1
print("Sum =", total)
word = input("Enter a word: ").lower()
count = 0
for ch in word:
if ch in "aeiou":
count += 1
print("Vowel count:", count)
| 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 |
| 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 |
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.