Flow of Control
Flow of Control
1. Sequential Flow
● Definition: Statements are executed one after another in the order in which they appear.
Example:
print("First statement")
print("Second statement")
●
● Definition: This allows the program to choose different paths based on conditions.
● Key Statements:
○ if: Executes a block of code if the condition is True.
○ elif: Executes a block of code if the previous if or elif conditions are False
and its condition is True.
○ else: Executes a block of code if all preceding conditions are False.
Example:
age = 20
if age >= 18:
print("Adult")
else:
print("Minor")
3. Looping (Repetition)
● Definition: This allows the program to execute a block of code multiple times.
● Key Statements:
○ for: Loops through a sequence (like a list, string, etc.) and executes the block
for each item.
○ while: Repeats a block of code as long as a condition is True.
○ break: Exits the loop.
○ continue: Skips the current iteration and moves to the next one.
Example:
# Using for loop
for i in range(5):
print(i)
● count += 1
Sequence
Here's a simple Python program that takes two numbers as input and prints the difference
between them:
In this program:
For example, if the user inputs 10 and 5, the program will output:
if condition:
# Block of code to execute if the condition is True
else:
# Block of code to execute if the condition is False
Explanation:
1. if condition:: This checks the condition. If the condition is True, the code indented
under the if block will be executed.
2. else:: This is optional and is executed when the condition is False. The code indented
under the else block will be executed.
Here’s a Python program to display the positive difference between two numbers:
Explanation:
1. We use abs() to calculate the absolute difference between the two numbers, which
ensures that the result is always positive, regardless of which number is larger.
2. The program then displays the positive difference.
For example:
If the user inputs 7 and 12, the output will be:
The positive difference between 7.0 and 12.0 is: 5.0
if number > 0:
else:
Explanation:
● if number > 0:: This checks if the number is greater than zero
(positive).
● elif number < 0:: This checks if the number is less than zero
(negative).
● else:: If the number is neither positive nor negative, it must be
zero, and the program will print "The number is zero."
Example:
If the user inputs 5, the output will be:
The number is positive.
if signal_color == "red":
else:
Explanation:
1.Input: The program takes the signal color as input (we use
.lower() to ensure that the input is case-insensitive).
2.Condition checks: The program uses if-elif-else statements to
check the color of the signal:
○ If it's Red, it displays "STOP!".
○ If it's Yellow, it displays "GET READY!".
○ If it's Green, it displays "GO!".
3.Else case: If the user enters an invalid color, it shows an error
message.
def calculator():
if operator == '+':
if num2 == 0:
else:
else:
calculator()
Explanation:
1.Inputs:
○ The program prompts the user for two numbers (num1 and num2)
and the operator (e.g., +, -, *, /).
2.Calculation:
○ The program checks the operator entered by the user and
performs the corresponding operation.
○ If the operator is +, it adds the numbers.
○ If the operator is -, it subtracts the second number from
the first.
○ If the operator is *, it multiplies the two numbers.
○ If the operator is /, it checks if the second number is 0
(to avoid division by zero) and divides the first number by
the second if the division is valid.
3.Error Handling:
○ If the operator is invalid (not one of +, -, *, or /), it
prints an error message.
2 Initialization: Set the initial value for the loop variable (e.g., i
= 1).
3 Condition Check: Check if the loop condition is true (e.g., i <= 5).
Flowchart Representation:
+-------------------+
| Start |
+-------------------+
|
v
+-------------------+
| Initialize i = 1 |
+-------------------+
|
v
+-------------------+
| i <= 5? |----No---> End
+-------------------+
|
v
+-------------------+
| Print i |
+-------------------+
|
v
+-------------------+
| Increment i (i = i+1)|
+-------------------+
|
v
Go back to check condition
Explanation:
Here's a simple Python program that prints the characters in the string "Python" using a
for loop:
# Given string
text = "Python"
print(char)
Here’s a Python program that prints the numbers in a given sequence using a for loop.
I'll assume you're referring to a range of numbers (e.g., from 1 to 10) as the sequence:
start = 1
end = 10
print(num)
This program will print the numbers from 1 to 10, one on each line:
5
6
10
Explanation:
● The program takes start and end as input from the user.
● It then loops through all numbers from start to end (inclusive).
● The if num % 2 == 0 condition checks if the number is even, and if it is, it prints the
number.
The range() function in Python is a built-in function used to generate a sequence of numbers,
which is commonly used in for loops. It can take one, two, or three arguments:
Syntax:
● start: The number where the sequence starts (default is 0 if not provided).
● stop: The number where the sequence ends (this number is not included in the
sequence).
● step: The difference between each number in the sequence (default is 1).
Examples:
Generates a sequence from 0 to the number just before the given number.
Output:
0
1
2
3
4
Here’s a Python program that prints the multiples of 10 for numbers in a given range
using the range() function:
Explanation:
● The program takes start and end as input from the user.
● The range(start, end + 1) function generates the sequence of numbers from
start to end (inclusive).
● The if num % 10 == 0 condition checks if the number is a multiple of 10.
● If the number is a multiple of 10, it is printed.
Example:
If you input start = 1 and end = 50, the output will be:
10
20
30
40
A while loop in Python repeatedly executes a block of code as long as the given
condition evaluates to True. Once the condition becomes False, the loop stops.
while condition:
# code to be executed as long as condition is True
Example:
count = 0
Explanation:
while True:
print("This will run forever!")
This loop will run indefinitely until manually stopped or interrupted, because the condition True
is always true.
Here’s a Python program that prints the first five natural numbers using a while loop:
Explanation:
1
2
3
4
5
In Python loops, the break and continue statements are used to alter the flow of the
loop. They are control statements that modify the behavior of for and while loops.
1. break Statement:
The break statement is used to exit or terminate the loop prematurely. When the break
statement is encountered, the loop stops executing and the program continues with the next
statement after the loop.
Example of break:
Output:
0
1
2
3
4
In this example, the loop stops when count reaches 5 due to the break statement, even
though the loop is set to run until count is less than 10.
2. continue Statement:
The continue statement is used to skip the current iteration of the loop and move to the next
iteration. When continue is encountered, the rest of the code inside the loop for that iteration
is skipped, and the loop proceeds with the next iteration.
Example of continue:
1
2
4
5
In this example, when num equals 3, the continue statement is executed, which skips the print
statement for that iteration, and the loop continues with the next value of num.
Summary:
● break: Exits the loop entirely and continues with the next statement after the loop.
● continue: Skips the current iteration and moves on to the next iteration of the loop.
Here's a Python program that will calculate the sum of all positive numbers entered by
the user. The Program will stop taking input and display the sum as soon as the user
enters a negative number.
while True:
# Take input from the user
number = float(input("Enter a positive number (or a negative
number to stop): "))
● The program uses an infinite while loop (while True) to continuously take input from
the user.
● If the user enters a negative number, the break statement is triggered, which exits the
loop.
● As long as the user enters a positive number, it is added to the total_sum.
● Once a negative number is entered, the loop stops, and the program prints the sum of
the positive numbers entered.
Example Output:
Explanation:
Example Outputs:
Enter a number: 7
7 is a prime number.
Enter a number: 8
8 is not a prime number.
Here are a few examples of programs using the continue statement in Python. The
continue statement skips the rest of the code inside a loop for the current iteration and
moves to the next iteration.
This program prints all the odd numbers from 1 to 10 by skipping even numbers using the
continue statement.
p
for num in range(1, 11):
if num % 2 == 0:
continue # Skip even numbers
print(num)
Output:
Copy
1
3
5
7
9
In this example, we will print numbers from 1 to 20, but skip those that are divisible by 3.
Output:
Copy
1
2
4
5
7
8
10
11
13
14
16
17
19
20
31
37
41
43
47
Syntax for Nested Loops:
● Outer Loop: The outer loop iterates over a range or sequence of values.
● Inner Loop: For each iteration of the outer loop, the inner loop iterates over its range.
● Both loops can perform their respective tasks inside their bodies.
Flowchart:
+-----------------+
| Start |
+-----------------+
|
v
+-------------------------+
| Outer Loop Condition? |<--------------------------+
+-------------------------+ |
|Yes/No |
v |
+---------------------+ |
| Inner Loop Condition?|---No--> End |
+---------------------+ |
|Yes/No |
v |
+----------------------------+ |
| Execute Inner Loop Body | |
+----------------------------+ |
| |
v |
+---------------------+ |
| Return to Inner Loop|<-----------------------------+
+---------------------+
|
v
+----------------------------+
| Return to Outer Loop |
+----------------------------+
|
v
+-----------------+
| End |
+-----------------+
This flowchart represents the sequential steps the program follows in executing nested loops:
checking conditions, executing the inner loop, and moving between the inner and outer loops
until all iterations are completed.
A nested loop in Python refers to a loop inside another loop. The inner loop runs completely
every time the outer loop runs once. Nested loops are typically used to iterate over
multi-dimensional data structures, such as lists of lists.
# Inner loop
for j in range(2):
print(f" Inner loop iteration {j}")
Output:
In this example:
This pattern creates a right-angled triangle where the number of stars increases with
each row.
Code:
# Right-Angle Triangle
n = 5 # Number of rows
for j in range(i):
print("*", end=" ")
EXplanation:
● Outer loop (for i in range(1, n + 1)): This loop runs for each row. The variable
i keeps track of the current row number (from 1 to 5).
● Inner loop (for j in range(i)): For each row, the inner loop prints stars (*) equal
to the row number. So, for row 1, 1 star is printed, for row 2, 2 stars are printed, and so
on.
● print(): This function moves to the next line after each row of stars is printed.
Output:
*
* *
* * *
* * * *
* * * * *
This pattern prints an inverted right-angle triangle, where the number of stars decreases with
each row.
Code:
Explanation:
● Outer loop (for i in range(n, 0, -1)): This loop starts from n (5) and
decrements down to 1. It determines the number of stars to be printed in each row.
● Inner loop (for j in range(i)): In each iteration of the outer loop, the inner loop
prints i stars. As i decreases with each row, the number of stars printed also
decreases.
● print(): This moves to the next line after each row.
Output:
* * * * *
* * * *
* * *
* *
*
3. Pyramid Pattern
This pattern creates a pyramid of stars, where the number of stars increases in the center, and
spaces are added to make the shape symmetric.
Code:
# Pyramid Pattern
n = 5 # Number of rows
for i in range(1, n + 1):
# Print spaces
for j in range(n - i):
print(" ", end="")
# Print stars
for k in range(2 * i - 1):
print("*", end="")
print() # Move to the next line after each row
Explanation:
● Outer loop (for i in range(1, n + 1)): This loop runs for each row in the
pyramid. The number of rows is determined by n.
● First inner loop (for j in range(n - i)): This loop prints spaces before the stars.
The number of spaces decreases as the row number (i) increases.
● Second inner loop (for k in range(2 * i - 1)): This prints the stars in the
pyramid. The number of stars in each row is 2*i - 1 (an odd number that increases as
i increases).
● print(): This moves to the next line after printing the spaces and stars for the current
row.
Output:
*
***
*****
*******
*********
4. Ptosis Pattern
The ptosis pattern creates a shape where the number of stars decreases in each row, similar to
an inverted right-angle triangle.
Code:
# Ptosis Pattern
n = 5 # Number of rows
for i in range(n, 0, -1):
for j in range(i):
print("*", end=" ")
print() # Move to the next line after each row
Explanation:
● Outer loop (for i in range(n, 0, -1)): This loop starts from n (5) and
decrements down to 1. For each value of i, it determines how many stars will be printed.
● Inner loop (for j in range(i)): This inner loop prints i stars for each row. As i
decreases with each iteration of the outer loop, the number of stars printed also
decreases.
● print(): Moves to the next line after printing all the stars for the current row.
Output:
* * * * *
* * * *
* * *
* *
*
5. Square of Stars
This pattern creates a square grid of stars, with the number of stars equal to the number of
rows.
Code:
# Square of Stars
n = 5 # Size of the square
for i in range(n):
for j in range(n):
print("*", end=" ")
print() # Move to the next line after each row
Explanation:
● Outer loop (for i in range(n)): This loop runs n times, where n is the number of
rows in the square grid.
● Inner loop (for j in range(n)): This inner loop prints n stars in each row.
● print(): This moves to the next line after printing all the stars in the current row.
Output:
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
Summary:
● Nested loops allow you to perform tasks like printing complex patterns.
● The outer loop controls the rows, while the inner loop controls the columns.
● You can use nested loops for various tasks, such as printing triangles, squares, and
pyramids, as shown in the examples above.
Indentation in Python:
4 Example of indentation:
if x > 10:
print("x is greater than 10") # Indented with 4 spaces
5 Indentation error:
Example:
if x > 10:
print("x is greater than 10") # This will cause an IndentationError
○
6 Nested blocks:
○
def greet():
print("Hello!") # Indented code inside the function
Quick Rules:
Program exercise