Chapter 06: Flow of Control
6.1 Introduction
When we write a program, Python normally executes statements one after another, in the order in which they appear. This is called sequential execution.
Example:
print("Start")
print("Processing")
print("End")
In many real-life situations, however, decisions must be made:
- If it rains, take an umbrella
- If marks are greater than 40, declare pass
- Repeat an action until a condition is met
Programs must therefore be able to:
- Choose between alternative paths
- Repeat certain instructions multiple times
- Stop or skip parts of execution when required
The ability to control the order of execution of statements is called flow of control.
Python provides control structures to manage this flow:
- Selection (decision making)
- Repetition (looping)
6.2 Selection (Decision Making)
Why Selection is Needed
A computer cannot “decide” on its own. It can only evaluate conditions and follow instructions based on results.
Selection allows a program to:
- execute certain statements only if a condition is true
- choose between multiple alternatives
In Python, selection is implemented using:
ifif–elseif–elif–else
All selection statements depend on Boolean expressions (True or False).
6.2.1 The if Statement
The simplest form of selection.
Logical Meaning
If a condition is true, perform an action. If it is false, do nothing.
Syntax
if condition:
statement(s)
Important Rules
- The condition must evaluate to
TrueorFalse - Statements under
ifmust be indented - No parentheses are required around the condition
Example
marks = 75
if marks >= 40:
print("Pass")
Explanation:
- Python checks
marks >= 40 - If true, it executes the indented statement
- If false, it skips it completely
6.2.2 The if–else Statement
Used when two alternative actions are possible.
Logical Meaning
If the condition is true, do one thing. Otherwise, do something else.
Syntax
if condition:
statement(s)
else:
statement(s)
Example
marks = 35
if marks >= 40:
print("Pass")
else:
print("Fail")
Explanation:
- Exactly one block will execute
elsehas no condition; it handles all remaining cases
6.2.3 The if–elif–else Statement
Used when multiple conditions must be checked.
Logical Meaning
Check conditions one by one. Execute the first block whose condition is true.
Syntax
if condition1:
statement(s)
elif condition2:
statement(s)
else:
statement(s)
Example
marks = 82
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 40:
print("Grade C")
else:
print("Fail")
Explanation:
- Conditions are checked top to bottom
- Once a condition is satisfied, remaining checks are skipped
elseacts as a default case
6.3 Indentation
Why Indentation is Critical in Python
Most programming languages use braces { } to define blocks.
Python does not.
Instead, Python uses indentation (spaces) to define:
- blocks of code
- scope of conditions and loops
This is not a style choice — it is a syntax rule.
Correct Indentation Example
if marks >= 40:
print("Pass")
print("Congratulations")
Both print statements belong to the if block.
Incorrect Indentation (Syntax Error)
if marks >= 40:
print("Pass")
Python raises an IndentationError because it cannot determine the block.
Key Rules
- All statements in a block must be indented equally
- Common practice: 4 spaces
- Mixing tabs and spaces causes errors
Indentation makes Python programs:
- cleaner
- more readable
- less ambiguous
6.4 Repetition (Loops)
Why Repetition is Needed
Many tasks involve repeating actions:
- printing numbers from 1 to 10
- calculating total marks for multiple subjects
- reading multiple inputs
Writing the same statement repeatedly is inefficient.
Loops allow us to repeat instructions automatically.
Python provides two main loops:
whilefor
6.4.1 The while Loop
Logical Meaning
*Repeat a block of code as long as a condition remains true.*
Syntax
while condition:
statement(s)
Example: Printing numbers 1 to 5
count = 1
while count <= 5:
print(count)
count = count + 1
Explanation:
- Condition is checked before every iteration
- Loop stops when condition becomes false
- Variable
countis called a loop control variable
Infinite Loop (Logical Error)
count = 1
while count <= 5:
print(count)
Why is this dangerous?
countnever changes- Condition always remains true
- Loop never ends
6.4.2 The for Loop
Used when the number of repetitions is known in advance.
Syntax
for variable in range(start, stop, step):
statement(s)
Example
for i in range(1, 6):
print(i)
Explanation:
range(1,6)generates numbers 1 to 5itakes one value at a time- Loop ends automatically
Comparison: while vs for
| Aspect | while | for | | - | - | – | | Condition based | Yes | No | | Count controlled manually | Yes | No | | Preferred when | repetitions unknown | repetitions known |
6.5 Break and Continue Statement
Sometimes we need extra control inside loops.
6.5.1 break Statement
Purpose
Immediately terminates the loop, regardless of condition.
Example
for i in range(1, 10):
if i == 5:
break
print(i)
Output:
1
2
3
4
Explanation:
- Loop stops when
i == 5 - Control moves outside the loop
6.5.2 continue Statement
Purpose
Skips the current iteration and moves to the next one.
Example
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
Explanation:
- When
i == 3, print is skipped - Loop continues normally
Difference Between break and continue
| break | continue | | | – | | Ends the loop | Skips current iteration | | Control exits loop | Control stays in loop |
6.6 Nested Loops
What Are Nested Loops?
A loop inside another loop is called a nested loop.
Used when a task requires repetition within repetition.
Example: Pattern Printing
for i in range(1, 4):
for j in range(1, 4):
print("*", end=" ")
print()
Output:
* * *
* * *
* * *
Explanation:
- Outer loop controls rows
- Inner loop controls columns
- Inner loop runs completely for each outer loop iteration
Example: Multiplication Table
for i in range(1, 6):
for j in range(1, 6):
print(i * j, end="\t")
print()
Key Conceptual Takeaways
- The
ifstatement is used for selection or decision making. - The looping constructs
whileandforallow sections of code to be executed repeatedly under some condition. forstatement iterates over arange of valuesor asequence.- The statements within the body of
forloop are executed till the range of values is exhausted. - The statements within the body of a
whileare executed over and over until the condition of the while is false. - If the condition of the while loop is initially false, the body is not executed even once.
- The statements within the body of the while loop must ensure that the condition eventually becomes false; otherwise, the loop will become an
infinite loop, leading to a logical error in the program. - TThe
breakstatement immediately exits a loop, skipping the rest of the loop’s body. Execution continues with the statement immediately following the body of the loop. - When a
continuestatement is encountered, the control jumps to the beginning of the loop for the next iteration. - A loop contained within another loop is called a
nested loop.