0% found this document useful (0 votes)
29 views28 pages

Flow of Control

The document explains control structures in Python, including sequential flow, conditional flow, and looping. It provides examples of each structure, such as if-else statements for decision-making and for/while loops for repetition. Additionally, it covers the use of break and continue statements to alter loop behavior and includes sample programs demonstrating these concepts.

Uploaded by

vanshpkp09
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views28 pages

Flow of Control

The document explains control structures in Python, including sequential flow, conditional flow, and looping. It provides examples of each structure, such as if-else statements for decision-making and for/while loops for repetition. Additionally, it covers the use of break and continue statements to alter loop behavior and includes sample programs demonstrating these concepts.

Uploaded by

vanshpkp09
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

There are several control structures that govern flow of program in Python.

1. Sequential Flow

●​ Definition: Statements are executed one after another in the order in which they appear.

Example:​

print("First statement")
print("Second statement")

●​

2. Conditional Flow (Decision-making) Selection

●​ 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)

# Using while loop


count = 0
while count < 5:
print(count)

●​ count += 1

Sequence

Here's a simple Python program that takes two numbers as input and prints the difference
between them:

# Input: Taking two numbers from the user


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Calculate the difference


difference = num1 - num2

# Output: Printing the difference


print("The difference between", num1, "and", num2, "is:", difference)

In this program:

1.​ We take two numbers as input from the user.


2.​ We calculate the difference between the two numbers.
3.​ Finally, we display the result.

For example, if the user inputs 10 and 5, the program will output:

The difference between 10.0 and 5.0 is: 5.0


Selection

The syntax for selection using an if-else statement in Python is as follows:

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:

# Input: Taking two numbers from the user


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Calculate the absolute difference


positive_difference = abs(num1 - num2)

# Output: Printing the positive difference


print("The positive difference between", num1, "and", num2, "is:",
positive_difference)

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 the user inputs 12 and 7, the output will also be:​



The positive difference between 12.0 and 7.0 is: 5.0

Here’s a Python program that checks whether a given number is


positive, negative, or zero:

# Input: Taking a number from the user

number = float(input("Enter a number: "))

# Check if the number is positive, negative, or zero

if number > 0:

print("The number is positive.")

elif number < 0:

print("The number is negative.")

else:

print("The number is zero.")

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 the user inputs -3, the output will be:​



The number is negative.

●​ If the user inputs 0, the output will be:​


The number is zero.

Here’s a Python program that displays an appropriate message based on


the color of the signal at a road crossing:

# Input: Taking the signal color as input

signal_color = input("Enter the color of the traffic signal


(Red/Yellow/Green): ").lower()

# Checking the color of the signal and displaying the appropriate


message

if signal_color == "red":

print("STOP! The signal is red.")

elif signal_color == "yellow":

print("GET READY! The signal is yellow.")

elif signal_color == "green":

print("GO! The signal is green.")

else:

print("Invalid color! Please enter Red, Yellow, or Green.")

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.

Write a program to create a simple calculator performing only four


basic operations using if elif python

# Function to perform calculation based on user input

def calculator():

# Taking input for the operation (operator) and the numbers

num1 = float(input("Enter first number: "))

operator = input("Enter operator (+, -, *, /): ")

num2 = float(input("Enter second number: "))

# Perform the operation based on the operator

if operator == '+':

result = num1 + num2

print(f"{num1} + {num2} = {result}")

elif operator == '-':

result = num1 - num2

print(f"{num1} - {num2} = {result}")

elif operator == '*':


result = num1 * num2

print(f"{num1} * {num2} = {result}")

elif operator == '/':

if num2 == 0:

print("Error! Division by zero.")

else:

result = num1 / num2

print(f"{num1} / {num2} = {result}")

else:

print("Invalid operator! Please enter one of the following: +,


-, *, /.")

# Call the function to perform calculation

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.

Flowchart for a for loop:

1 Start: The program starts.

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).

○​ If True, proceed to the next step.


○​ If False, exit the loop and end the process.
4.​ Body of the loop: Execute the statements inside the loop (e.g., print(i)).
5.​ Update Loop Variable: Update the loop variable (e.g., i = i + 1).
6.​ Repeat: Go back to step 3 to check the condition again.

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:

●​ Step 1: Start the program.


●​ Step 2: Initialize the loop variable (i = 1).
●​ Step 3: Check if the condition (i <= 5) is true.
●​ Step 4: If true, print i.
●​ Step 5: Increment i (e.g., i = i + 1).
●​ Step 6: Repeat steps 3-5 until the condition becomes false

Here's a simple Python program that prints the characters in the string "Python" using a
for loop:

# Given string

text = "Python"

# Loop through each character in the string

for char in text:

print(char)

When you run this code, it will output:


P

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:

# Define the sequence range (1 to 10 as an example)

start = 1

end = 10

# Loop through the range and print each number

for num in range(start, end + 1):

print(num)

This program will print the numbers from 1 to 10, one on each line:

5
6

10

Here is the Python program to print even numbers in a given sequence .

# Input the starting and ending numbers


start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))

# Loop through the sequence and print even numbers


for num in range(start, end + 1):
if num % 2 == 0:
print(num)

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:

range(start, stop, step)

●​ 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:

1. Using range() with 1 argument:

Generates a sequence from 0 to the number just before the given number.

for num in range(5):


print(num)

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:

# Input the starting and ending numbers


start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))

# Loop through the range and print multiples of 10


for num in range(start, end + 1):
if num % 10 == 0:
print(num)

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.

Here’s the basic syntax for a while loop:

while condition:
# code to be executed as long as condition is True

Example:

count = 0

while count < 5:


print(count)
count += 1 # This increments count by 1

Explanation:

●​ The loop starts by checking if count is less than 5.


●​ As long as the condition count < 5 is True, the code inside the loop will execute,
printing the value of count and then incrementing it.
●​ Once count reaches 5, the condition becomes False, and the loop exits.

Infinite loop example:

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:

# Initialize the variable


num = 1

# While loop to print first five natural numbers


while num <= 5:
print(num)
num += 1 # Increment the value of num

Explanation:

●​ We start with num = 1 since 1 is the first natural number.


●​ The while loop runs as long as num <= 5.
●​ Each time the loop runs, it prints the current value of num, then increments num by 1.
●​ When num becomes 6, the condition num <= 5 becomes false, and the loop stops.

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:

# Example using a while loop


count = 0

while count < 10:


if count == 5:
break # Exit the loop when count is 5
print(count)
count += 1

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:

# Example using a for loop


for num in range(1, 6):
if num == 3:
continue # Skip the current iteration when num is 3
print(num)
Output:

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.

# Initialize the sum variable


total_sum = 0

while True:
# Take input from the user
number = float(input("Enter a positive number (or a negative
number to stop): "))

# If the user enters a negative number, stop the loop


if number < 0:
break

# Add the positive number to the total sum


total_sum += number

# Display the sum of all positive numbers


print("The sum of all positive numbers entered is:", total_sum)
Explanation:

●​ 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:

Enter a positive number (or a negative number to stop): 10


Enter a positive number (or a negative number to stop): 20
Enter a positive number (or a negative number to stop): 5
Enter a positive number (or a negative number to stop): -1
The sum of all positive numbers entered is: 35.0

Here’s a Python program to check whether a number is prime or not.

# Take input from the user


number = int(input("Enter a number: "))

# Check if the number is less than or equal to 1


if number <= 1:
print(f"{number} is not a prime number.")
else:
# Flag to check if number is prime
is_prime = True

# Check divisibility from 2 to the square root of the number


for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
is_prime = False # The number is divisible by i, so it's
not prime
break

# Display the result


if is_prime:
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")

Explanation:

1.​ The user inputs a number.


2.​ The program checks if the number is less than or equal to 1. If so, it's not prime.
3.​ It then checks divisibility starting from 2 up to the square root of the number. This is an
efficient way to check for factors.
4.​ If any divisor is found, the is_prime flag is set to False, and the loop stops (break).
5.​ The program prints whether the number is prime or not based on the is_prime flag.

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.

1. Skipping even numbers in a loop

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

2. Skipping numbers divisible by 3

In this example, we will print numbers from 1 to 20, but skip those that are divisible by 3.

for num in range(1, 21):


if num % 3 == 0:
continue # Skip numbers divisible by 3
print(num)

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:

for outer_variable in range(outer_limit):


# Outer loop body
for inner_variable in range(inner_limit):
# Inner loop body

●​ 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 for Nested Loop

Here is the flowchart for understanding how a nested loop works:

1.​ Start: The process begins.


2.​ Outer Loop Condition: Check if the outer loop's condition is satisfied (e.g., i <
outer_limit).
○​ If False, end the program.
○​ If True, proceed to the inner loop.
3.​ Inner Loop Condition: Check if the inner loop's condition is satisfied (e.g., j <
inner_limit).
○​ If False, return to the outer loop and move to the next iteration of the outer loop.
○​ If True, execute the inner loop body.
4.​ Execute Inner Loop Body: Perform the task for the current inner loop iteration.
5.​ Return to Inner Loop: After the inner loop body is executed, go back and check the
inner loop condition again.
6.​ Outer Loop Iteration: After all inner loop iterations are done, go back and check the
outer loop condition for the next iteration.
7.​ End: When both loops complete, the program ends.

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.

Here’s a basic example of a nested loop:


# Outer loop
for i in range(3):
print(f"Outer loop iteration {i}")

# Inner loop
for j in range(2):
print(f" Inner loop iteration {j}")

Output:

Outer loop iteration 0


Inner loop iteration 0
Inner loop iteration 1
Outer loop iteration 1
Inner loop iteration 0
Inner loop iteration 1
Outer loop iteration 2
Inner loop iteration 0
Inner loop iteration 1

In this example:

●​ The outer loop runs 3 times (i.e., i takes values 0, 1, 2).


●​ The inner loop runs 2 times for each iteration of the outer loop (i.e., j takes values 0, 1).

1. Right-Angle Triangle Pattern

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 i in range(1, n + 1):

for j in range(i):
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. 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:

*
* *
* * *
* * * *
* * * * *

2. Inverted Right-Angle Triangle Pattern

This pattern prints an inverted right-angle triangle, where the number of stars decreases with
each row.

Code:

# Inverted Right-Angle Triangle


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. 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:

1.​ Indentation in Python is mandatory:


○​ Python uses indentation to define code blocks (such as loops,
conditionals, functions, and classes).
○​ Unlike other languages (like C, Java), Python does not use curly braces {}
to define blocks of code; indentation is used instead.
2.​ Consistency is key:
○​ You must be consistent with the number of spaces or tabs you use for
indentation.
○​ Mixing spaces and tabs can lead to errors.
3.​ Standard practice:
○​ The Python PEP 8 style guide recommends using 4 spaces per indentation
level.
○​ Avoid mixing tabs and spaces.

4 Example of indentation:​

if x > 10:
print("x is greater than 10") # Indented with 4 spaces

5 Indentation error:

○​ If you forget to indent or mis-indent your code, Python will raise an


IndentationError.

Example:​

if x > 10:
print("x is greater than 10") # This will cause an IndentationError

○​

6 Nested blocks:

○​ If you have multiple levels of logic (loops or conditions inside functions),


you must indent each level.

Example of nested loops:​



for i in range(3): # Outer loop
for j in range(2): # Inner loop
print(i, j)

○​

7 Indentation with functions:

○​ The code inside functions is indented to indicate the function's body.


def greet():
print("Hello!") # Indented code inside the function

8 Tools for managing indentation:

○​ Most modern code editors or IDEs automatically manage indentation (e.g.,


VSCode, PyCharm).
○​ You can configure editors to use 4 spaces instead of tabs for indentation.

Quick Rules:

●​ 4 spaces per level.


●​ Do not mix tabs and spaces.
●​ Python relies on indentation for logical grouping, so it must be consistent.

Program exercise

You might also like