CPT211 - Lecture Note4
CPT211 - Lecture Note4
I. Introduc4on
Flow control is a fundamental concept in programming that allows the execu8on of code to
be altered based on certain condi8ons. Python provides several flow control statements to
control the flow of execu8on, including if-else statements, loops, and other control structures.
This lecture note will cover the various flow control mechanisms in Python and provide
detailed and concrete examples to illustrate the concepts.
-1-
The elif statement allows you to check for mul8ple condi8ons in a chain and execute different
blocks of code based on the first condi8on that is true.
Syntax:
if condition1:
# code block to execute if condition1 is true
elif condition2:
# code block to execute if condition2 is true and condition1 is false
else:
# code block to execute if all previous conditions are false
IV. Loops
Loops are used to repeatedly execute a block of code un8l a specified condi8on is met. Python
provides two types of loops: for loop and while loop.
1. For Loop
The for loop iterates over a sequence (such as a list, tuple, or string) or other iterable
objects.
Syntax:
for item in sequence:
# code block to execute
-2-
Example 8: Finding the sum of numbers using a while loop
num_sum = 0
num = 1
while num <= 10:
num_sum += num
num += 1
print("Sum:", num_sum)
V. Control Structures
Python provides addi8onal control structures to modify the flow of execu8on.
1. Break Statement.
The break statement is used to exit a loop prematurely.
Example: Finding the first even number in a list
numbers = [1, 3, 5, 6, 7, 8, 9]
for num in numbers:
if num % 2 == 0:
print("The first even number is:", num)
break
2. Con4nue Statement.
The con8nue statement is used to skip the rest of the code block and move to the next
itera8on of the loop.
Example: Prin8ng odd numbers in a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for num in numbers:
if num % 2 == 0:
continue
print(num)
VII. Conclusion
Flow control is essen8al for controlling the execu8on of code based on certain condi8ons.
Python provides if-else statements, loops (for and while), and control structures like break and
con8nue to facilitate flow control.
By understanding and u8lizing these flow control mechanisms effec8vely, you can write more
efficient and versa8le Python programs.
-3-