Control Flow Statement

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

Agenda

In this class we will discuss about Python Conditional Statements and Loops:

• What is Conditional Statements


• Importance of Conditional Statements
• Types of Conditional Statements
• If/ else
• Membership operators with conditonal statements
• Python Loops
• For Loop
• Use of the for loop for different data structures
• While Loop
• Use of the while loop for different data structures
• A Short Program: Rock, Paper, Scissors

Conditonal Statements
• Conditional statements, also known as control structures, are programming
constructs that allow the execution of different code blocks based on specific
conditions. They enable a program to make decisions and choose different paths of
execution based on the evaluation of one or more conditions. Conditional
statements are an essential part of programming languages and play a crucial role in
controlling the flow of a program.

• In a conditional statement, the program evaluates a condition or set of conditions


and executes different blocks of code based on the outcome. The condition(s) can be
expressed as logical expressions or comparisons that evaluate to either true or false.
Based on the evaluation of the condition(s), the program chooses the appropriate
block of code to execute.

Importance of Conditional Statements


Conditional statements are used in programming to make decisions and control the flow of
execution based on specific conditions. They are crucial for creating logic and implementing
different behaviors in a program. Here are some common use cases where conditional
statements are employed:

1. Branching: Conditional statements, such as if, else, and elif (else if), are used to
create branching paths in a program. They allow you to execute different blocks of
code based on specific conditions. For example, you can check if a certain condition
is true and perform one action, or if it is false, perform a different action.
2. Looping: Conditional statements are often used in conjunction with looping
constructs, such as while and for loops, to control the iteration process. By checking
a condition, you can decide whether to continue or exit a loop. This allows you to
repeat a block of code until a specific condition is met or iterate over a collection of
items.

3. Data Filtering: Conditional statements are used to filter and select specific subsets of
data based on certain conditions or criteria. For example, you may filter data to
include only rows where a particular column meets specific conditions or extract
data points that satisfy certain constraints.

4. Data Transformation: Conditional statements assist in transforming data based on


specific conditions. You can apply conditional operations to modify or recode values,
perform mathematical transformations, or convert data to different representations
based on predefined conditions.

5. Decision-Making and Predictions: Conditional statements are applied in decision-


making processes and predictions. They allow you to incorporate specific conditions
or rules to make decisions or predictions based on certain data patterns or features.

Types of Condtional Statements:-


IF Statement
• The if statement is a conditional statement in Python that allows you to execute a block
of code if a certain condition is true. It provides the ability to make decisions and control
the flow of execution based on specific conditions.
• The Syntax for the if statement is:
if condition:
# Code block to execute if the condition is true

1. if keyword: The if keyword is the starting point of the if statement. It is followed by a


condition that will be evaluated.

2. Condition: The condition is an expression or a logical statement that is evaluated to


either True or False. It determines whether the code block following the if statement
should be executed.

3. Code block: The code block is a set of indented statements that will be executed if
the condition evaluates to True. It is typically indented using spaces or tabs to
denote that it belongs to the if statement.
[Flow chart of if statement]

```python
num = 10
if num > 0:
print("The number is positive.")
else:
print("The number is non-positive.")
```

# Finding the greatest number:


num1 = 61
num2 = 52
num3 = 78
max_num = num1
if num2 > max_num:
max_num = num2
if num3 > max_num:
max_num = num3
print("The maximum of the three numbers is:", max_num)
# Output: The maximum of the three numbers is: 78

1. SHORT HAND IF
• The shorthand if conditional statement, also known as the ternary operator, is a compact
way to write an if-else statement in Python. It allows you to write a single line of code
that evaluates a condition and returns one of two possible values based on the result of
the condition.

Syntax: python value_if_true if condition else value_if_false

• value_if_true: This is the value that will be returned if the condition is true.

• condition: This is the condition that will be evaluated. It can be any expression that
evaluates to a boolean value.

• value_if_false: This is the value that will be returned if the condition is false.

num = 7
result = "even" if num % 2 == 0 else "odd"
print(result)

age = 25
message = "You are old enough to vote." if age >= 18 else "You are not
old enough to vote yet."
print(message)

1. if-else Statement
• The if-else statement is a type of conditional statement in programming that allows you
to execute different blocks of code based on a certain condition. The if-else statement
consists of one if statement and one else statement.

Syntax:

if condition:
# Code to be executed if condition is true
else:
# Code to be executed if condition is false

• if condition:: This is the starting point of the conditional statement. The keyword if
is followed by a condition enclosed in parentheses. The condition is a logical
expression that evaluates to either True or False. If the condition is true, the code
block indented below this line will be executed.

• Code to be executed if condition is true: This is a comment indicating that the code
block following the if statement will be executed if the condition is true. The code
block consists of one or more statements that are indented by a consistent amount
of whitespace. These statements will be executed only if the condition is true.

• else:: This keyword introduces an optional block of code that will be executed if the
condition in the if statement is false. If the condition is false, the code block indented
below this line will be executed.

• Code to be executed if condition is false: This is a comment indicating that the code
block following the else statement will be executed if the condition in the if
statement is false. The code block, like the one under the if statement, consists of
one or more statements indented consistently.

age = 15
age_limit=18
if age >= age_limit:
print("You are old enough to vote!")
else:
print("You are not old enough to vote yet.")
# Output: You are not old enough to vote yet.

1. Short Hand If-Else


• The shorthand if-else conditional statement, also known as the ternary operator, is a
condensed version of the if-else statement in Python. It allows you to write an if-else
statement on a single line of code, making the code more concise and easier to read.

Syntax:

value_if_true if condition else value_if_false

• value_if_true: This is the value that will be returned if the condition is true.

• condition: This is the condition that will be evaluated. It can be any expression that
evaluates to a boolean value.

• value_if_false: This is the value that will be returned if the condition is false.
num = 7
result = "even" if num % 2 == 0 else "odd"
print(result)
# output: odd

1. if-elif-else:
• The if-elif-else statement is a type of conditional statement in Python that allows you to
check multiple conditions and execute different blocks of code based on the results. The
if-elif-else statement consists of one if statement, zero or more elif statements, and one
optional else statement.

Syntax:

if condition1:
# Code to be executed if condition1 is true
elif condition2:
# Code to be executed if condition2 is true
elif condition3:
# Code to be executed if condition3 is true
else:
# Code to be executed if all conditions are false

• if condition1:: This is the starting point of the conditional statement. The keyword if
is followed by a condition enclosed in parentheses. If the condition1 evaluates to
true, the code block indented below this line will be executed.

• Code to be executed if condition1 is true: This is a comment indicating that the code
block following the if statement will be executed if condition1 is true. The code
block consists of one or more statements indented consistently.

• elif condition2:: The keyword elif stands for "else if" and is used to check an
additional condition if the previous condition(s) in the if-elif-else chain is false. If
condition1 is false and condition2 evaluates to true, the code block indented below
this line will be executed.

• Code to be executed if condition2 is true: This comment signifies that the code block
following the elif statement will be executed if condition2 is true. The code block is
indented consistently.

• elif condition3:: Similarly, the elif keyword is used to check another condition if the
previous conditions are false. If condition1 and condition2 are both false and
condition3 evaluates to true, the code block indented below this line will be
executed.

• Code to be executed if condition3 is true: This comment denotes that the code block
following the second elif statement will be executed if condition3 is true. The code
block is indented consistently.
• else:: This keyword introduces an optional block of code that will be executed if all
previous conditions in the if-elif-else chain are false. If none of the conditions
(condition1, condition2, and condition3) are true, the code block indented below
this line will be executed.

• Code to be executed if all conditions are false: This comment indicates that the code
block following the else statement will be executed if all conditions in the if-elif-else
chain are false. The code block is indented consistently.

# Finding the grade of your score


score=87
if score >= 90:
print("You got an A!")
elif score >= 80:
print("You got a B.")
elif score >= 70:
print("You got a C.")
elif score >= 60:
print("You got a D.")
else:
print("You got an F.")
#Output: You got a B.

# Finding the Day of the week:


day = input("Enter a day of the week: ")
if day == "Monday":
print("It's Monday, the start of a new week.")
elif day == "Friday":
print("It's Friday, the end of the workweek!")
elif day == "Saturday" or day == "Sunday":
print("It's the weekend!")
else:
print("It's a weekday.")

1. NESTED-IF:
• A nested if statement is a conditional statement that is used inside another conditional
statement. It is used when you need to test for multiple conditions and perform different
actions based on the outcome of each condition.

Syntax:

if condition1:
# code to be executed if condition1 is true
if condition2:
# code to be executed if condition2 is true
else:
# code to be executed if condition2 is false
else:
# code to be executed if condition1 is false
• condition1: This is the outer condition that will be evaluated. If this condition is
true, the program will execute the code inside the outer if statement. If it is false, the
program will skip to the else statement.

• condition2: This is the inner condition that will be evaluated if condition1 is true. If
this condition is true, the program will execute the code inside the inner if
statement. If it is false, the program will execute the code inside the inner else
statement.

• code to be executed: This is the code that will be executed if the condition is true.

age = 18
if age >= 18:
print("You are old enough to vote.")
if age >= 21:
print("And you are old enough to drink.")
else:
print("But you are not old enough to drink.")
else:
print("You are not old enough to vote or drink.")
# Output:You are old enough to vote.
# Output:But you are not old enough to drink.

num = 15
if num > 0:
print("The number is positive.")
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
else:
print("The number is not positive.")
print("End of program.")
# output:The number is positive.
# output:The number is odd.
# output:End of program.

Membership operators with conditonal statements Membership operators are used in Python
to test whether a value is a member of a sequence or collection.Membership operators are often
used with conditional statements to check if a value is present or absent in a sequence or
collection. They are useful when working with lists, tuples, sets, and dictionaries.

Types of Membership operators:

in operator(in):

The in operator returns True if the left operand is found in the right operand. It is used to test
whether a value is a member of a sequence or collection.
numbers = [1, 2, 3, 4, 5]
if 3 in numbers:
print("3 is in the list.")
else:
print("3 is not in the list.")

not in operator(not in) The not in operator returns True if the left operand is not found in the
right operand. It is used to test whether a value is not a member of a sequence or collection.

numbers = [1, 2, 3, 4, 5]
if 6 not in numbers:
print("6 is not in the list.")
else:
print("6 is in the list.")

Python Loops
In Python, a loop is a programming construct that allows you to repeat a block of code multiple
times. There are two main types of loops in Python: the for loop and the while loop.

The for loop allows you to iterate over a sequence of items, such as a list, tuple, or string, and
execute a block of code once for each item in the sequence. The while loop allows you to execute
a block of code repeatedly as long as a certain condition is true.

Loops are a powerful and flexible programming construct, and are used in a wide variety of
programming tasks, such as data processing, web development, gaming, and robotics. They can
help you to write efficient and concise code, and are an essential tool for any Python
programmer.

For Loop
In Python, a for loop is a programming construct that allows you to iterate over a sequence of
items, such as a list, tuple, or string. The loop executes a block of code once for each item in the
sequence, allowing you to perform the same action on each item in the sequence.

Advantages of For Loop


• Simplicity: The for loop is a simple and easy-to-understand construct that is widely
used in Python programming.

• Flexibility: For loops can be used with a variety of data structures, including lists,
tuples, strings, and dictionaries.

• Efficiency: For loops are an efficient way to iterate over large sequences of items,
and are often faster than other types of loops.

• Readability: For loops can make your code more readable, by allowing you to
perform the same action on each item in a sequence in a clear and concise manner.
Real-life application of the For Loop
• Processing data: For loops are commonly used in data processing tasks, such as
reading data from a file or database and performing calculations on the data.

• Web development: For loops are used in web development to display dynamic
content on web pages, such as iterating over a list of blog posts to display them on a
webpage.

• Gaming: For loops can be used in game development to perform actions on each
element of a game world, such as updating the position and status of each game
object.

• Robotics: For loops are used in robotics programming to iterate over sensor data
and perform calculations on the data to control the behavior of the robot.

Syntax:-
for item in sequence:
# Code block

• Loop variable: A variable that represents the current iteration of the loop. It is
typically used to control the number of iterations.

• Iteration sequence: A collection of values or elements over which the loop iterates.
This can be an array, a list, a range of numbers, or any other iterable data structure.

• Loop body: The code block that is executed repeatedly for each iteration of the loop.

• Loop control: The mechanism that manages the flow of the loop, including
initialization, condition checking, and incrementing or updating the loop variable.

# Printing Fruits from a List


fruits = ['apple', 'banana', 'cherry']

for fruit in fruits:


print(fruit)

# Output:
apple
banana
cherry

Use of the for loop for different data structures


• For loop with Dictionaries
person = {'name': 'John', 'age': 30, 'city': 'New York'}
for key in person:
print(key, ':', person[key])
# Output:
# name : John
# age : 30
# city : New York

• For loop with Strings


word = 'Python'
for letter in word:
print(letter)
# Output:
# P
# y
# t
# h
# o
# n

• For loop with Tuples


colors = ('red', 'green', 'blue')
for color in colors:
print(color)
# Output:
# red
# green
# blue

• For loop with Lists


fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry

for loop with the continue statement


• The continue statement is a control flow statement in Python that is used to skip over
certain parts of a for loop.
• Continue is a keyword that allows you to skip over certain iterations of a for loop, without
stopping the entire loop. It is useful when you need to skip over certain items in a
sequence, based on some condition.

Real life application:

1. Data filtering: When processing a collection of data, the continue statement can be
used to skip certain elements that do not meet specific criteria or conditions. For
example, in data analysis or filtering tasks, you can use the continue statement to
skip data points that are outliers or don't satisfy certain criteria, allowing you to
focus on relevant data.

2. Error handling: The continue statement can be used in error handling situations to
skip processing or execution for certain elements that might cause errors or
exceptions. For instance, if you are iterating over a list of files to perform operations,
you can use the continue statement to skip files that cannot be accessed or have
errors.

3. Event handling: In event-driven programming or handling events in user interfaces,


the continue statement can be used to skip the processing of certain events or event
handlers based on specific conditions. This allows you to selectively handle or
bypass certain events and focus on others.

Syntax:

for item in sequence:


if condition:
continue
# Rest of the code

1. Initialization: Before the loop begins, the iteration variable (item) is initialized with
the first item from the sequence.

2. Condition: The loop continues as long as there are more items in the sequence. It
automatically handles iterating through each item until there are no more items.

3. Iteration: In each iteration, the current item from the sequence is assigned to the
iteration variable (item). The code inside the loop is executed sequentially until the
continue statement is encountered.

4. Condition Check: When the continue statement is reached, the condition is


evaluated. If the condition is true, the remaining statements in the current iteration
are skipped, and the loop moves on to the next iteration. If the condition is false, the
execution continues with the rest of the code inside the loop.

5. Rest of the Code: After the continue statement, the remaining statements in the loop
body are skipped for the current iteration if the condition is true. If the condition is
false, the execution continues with the rest of the code inside the loop.

6. Update: After executing the loop body (excluding the skipped statements if the
condition is true), the loop updates the iteration variable (item) to the next item in
the sequence. This process continues until there are no more items in the sequence.

# use of continue statement


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers:
if number % 2 == 0: # If the number is even
continue # Skip over the rest of the loop
print(number) # Otherwise, print the number
# Output:
# 1
# 3
# 5
# 7
# 9

for loop with the break statement


• The break statement is a control flow statement in Python that is used to exit a for loop
prematurely.
• break is a keyword that allows you to stop a for loop from continuing to iterate through
items in a sequence, even if the loop has not finished iterating through all the items in
the sequence.

Real life application:

1. Search and retrieval: When searching for a specific element in a collection or


sequence, the break statement can be used to exit the for loop once the desired
element is found. This is useful when you want to stop searching further and
prevent unnecessary iterations.

2. Data validation: In data validation scenarios, the break statement can be used to
break out of a loop when an invalid or unexpected condition is encountered. For
instance, if you are validating user input or data from a source, you can use the
break statement to exit the loop when an invalid value is detected.

3. Error handling: In error handling scenarios, the break statement can be used to stop
the execution of a loop when an error or exceptional condition occurs. This allows
you to handle the error separately outside the loop or jump to an error-handling
routine.
syntax:

for item in sequence:


if condition:
break
# Rest of the code

• Initialization: Before the loop begins, the iteration variable (item) is initialized with
the first item from the sequence.

• Condition: The loop continues as long as there are more items in the sequence. It
automatically handles iterating through each item until there are no more items.
• Iteration: In each iteration, the current item from the sequence is assigned to the
iteration variable (item). The code inside the loop is executed sequentially until the
break statement is encountered.

• Condition Check: When the break statement is reached, the condition is evaluated. If
the condition is true, the loop is terminated immediately, and the program flow
moves to the code following the loop. If the condition is false, the execution
continues with the rest of the code inside the loop.

• Rest of the Code: After the break statement, the remaining statements in the loop
body are not executed. If the break statement is encountered, the loop terminates,
and the program execution continues with the code following the loop.
Printing Fruits Until Orange is Found using the break statement

fruits = ['apple', 'banana', 'cherry', 'orange', 'pear']

for fruit in fruits:


if fruit == 'orange': # If we find an orange
break # Stop the loop
print(fruit)
# Output:
# apple
# banana
# cherry

Use of For loop with pass keyword:


When using the pass keyword in a for loop, it acts as a placeholder statement that allows you to
create a loop structure without having to write any code inside the loop. It's like telling Python to
"pass over" that part of the loop for now and focus on defining the loop's structure first. You can
come back later and fill in the code you want to execute inside the loop. The pass keyword
ensures that the loop remains syntactically correct even when there is no specific code to
execute at the moment. It provides flexibility in building the loop's structure while deferring the
implementation of its functionality until later.

Syntax:

for item in sequence:


pass

• Initialization: Before the loop begins, the iteration variable (item) is initialized with
the first item from the sequence.
• Condition: The loop continues as long as there are more items in the sequence. It
automatically handles iterating through each item until there are no more items.

• Iteration: In each iteration, the current item from the sequence is assigned to the
iteration variable (item). Since we use the pass keyword, there is no specific code
executed within the loop body for each item.

• Loop Body: The pass statement acts as a placeholder inside the loop body, indicating
that no code needs to be executed for each iteration. It ensures that the loop
remains syntactically correct.

• Update: After executing the loop body (in this case, the pass statement), the loop
updates the iteration variable (item) to the next item in the sequence. This
continues until there are no more items in the sequence.
Printing Odd Numbers from a List

numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
pass
else:
print(num)

#output:
1
3
5

Printing Student Details (Except students from Grade B)

students = [
{'name': 'John', 'age': 20, 'grade': 'A'},
{'name': 'Emily', 'age': 19, 'grade': 'B'},
{'name': 'Michael', 'age': 21, 'grade': 'A'},
{'name': 'Sophia', 'age': 20, 'grade': 'B'},
{'name': 'Daniel', 'age': 19, 'grade': 'C'}
]

for student in students:


if student['grade'] == 'B':
pass
else:
print(f"Name: {student['name']}, Age: {student['age']}")

# output:
Name: John, Age: 20
Name: Michael, Age: 21
Name: Daniel, Age: 19
Nested for loop:-
A nested for loop is a loop construct that consists of one for loop nested inside another for loop.
This creates a hierarchical structure where the inner for loop is completely contained within the
outer for loop. Each iteration of the outer for loop triggers a series of iterations of the inner for
loop.

syntax:

for variable_outer in sequence_outer:


# Code block for the outer for loop
for variable_inner in sequence_inner:
# Code block for the inner for loop
# Code block after the inner for loop

In the nested for loop, there are two sequences: sequence_outer for the outer loop and
sequence_inner for the inner loop. The code within the outer for loop is executed repeatedly for
each element in sequence_outer. Inside the outer loop, the inner for loop is executed repeatedly
for each element in sequence_inner. The flow of execution progresses from the outer loop to the
inner loop, and then back to the outer loop, until all iterations of both loops are completed.

Example of the Nested For Loop:-

Iterating through a 2D Grid:-

for i in range(1, 4):


for j in range(1, 4):
print('i=' + str(i) + ', j=' + str(j))
# Output:
# i=1, j=1
# i=1, j=2
# i=1, j=3
# i=2, j=1
# i=2, j=2
# i=2, j=3
# i=3, j=1
# i=3, j=2
# i=3, j=3

Finding prime numbers in a range using nested for loops:

# Example: Finding prime numbers in a range using nested for loops


start = 1
end = 20
print("Prime numbers between", start, "and", end, "are:")

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


if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)

# output:
Prime numbers between 1 and 20 are:
2
3
5
7
11
13
17
19

Comphresion
In Python, a comprehension is a concise and efficient way to create new lists, dictionaries, sets,
or generators from existing iterables like lists or strings. It allows you to write code in a more
compact form by combining looping and conditional logic.

Comprehensions are especially useful when you want to transform or filter data quickly without
writing lengthy loops. They make your code more readable and reduce the number of lines you
need to write.

Types of comprehensions in python:

1. List Comprehension: List comprehensions are used to create new lists by iterating over
an existing iterable and applying an expression to each element.
# List Comprehension
numbers = [1, 2, 3, 4, 5]
squares = [num ** 2 for num in numbers]
print(squares)
# Output:- [1, 4, 9, 16, 25]

1. Dictionary Comprehension: Dictionary comprehensions allow you to create new


dictionaries by iterating over an existing iterable and defining key-value pairs based on
an expression.
# Dictionary Comprehension
numbers = [1, 2, 3, 4, 5]
squares_dict = {num: num ** 2 for num in numbers}
print(squares_dict)
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

1. Set Comprehension: Set comprehensions are used to create new sets by iterating over an
existing iterable and applying an expression to each element. Set comprehensions
automatically remove duplicate values.
# Set Comprehension
numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1]
unique_squares = {num ** 2 for num in numbers}
print(unique_squares)
# Output: {1, 4, 9, 16, 25}

While Loop
A while loop is a control flow statement that allows code to be executed repeatedly while a
specified condition is true. The code inside the loop will continue to execute as long as the
condition remains true, and will stop executing as soon as the condition becomes false.

While loop in Python has the following advantages:


• Flexibility: It can solve various programming problems and repeat instructions as many
times as needed based on a condition.
• Condition-based execution: It executes a block of code repeatedly based on a condition,
which is useful for tasks where the number of iterations is not known in advance or can
vary.
• Simplifies tasks: It can simplify complex tasks by encapsulating complex logic within a
loop construct, making the code more readable and easier to understand.

Real life applications:


• Input validation in software applications
• Simulation and modeling of various systems and processes
• Game development to control game logic and update game state
• Control systems to implement closed-loop feedback systems
• Data processing of large datasets to perform iterative calculations and filter data.

Syntax
# use of the while loop
x = 0
while x < 5:
print(x)
x += 1
# output:
0
1
2
3
4

i = 1
while i <= 10:
if i % 2 == 0:
print(i)
i += 1
# output:
2
4
6
8
10

use of while loop with different data structures


• While Loop with List
# While loop with list
numbers = [1, 2, 3, 4, 5]
i = 0
while i < len(numbers):
print(numbers[i])
i += 1
# Output: 1 2 3 4 5

• While Loop with String


# While loop with string
message = "Hello, world!"
i = 0
while i < len(message):
print(message[i])
i += 1
# Output: H e l l o , w o r l d !

• While Loop with Set


# define a set of numbers
numbers = {1, 2, 3, 4, 5}
# define a variable to keep track of the sum of numbers
sum = 0
# define a while loop to iterate over the numbers set
while len(numbers) > 0:
# remove the first number in the set
num = numbers.pop()
# add the number to the sum
sum += num
# print the sum of the numbers
print("The sum of the numbers is:", sum)
# Output: The sum of the numbers is: 15

• While Loop with Dictionary


# While loop with dictionary
person = {"name": "Alice", "age": 30, "gender": "Female"}
keys = list(person.keys())
i = 0
while i < len(keys):
key = keys[i]
value = person[key]
print(key, value)
i += 1
# Output: name Alice age 30 gender Female

Use of the while loop with the break statement


• break statement: TThe break statement in Python is used to exit or terminate a loop
prematurely. It is commonly used with the while loop to control the loop's execution and
break out of the loop based on a specific condition.

Real life application:

1. Condition-based Loop Termination: With the while loop, the break statement allows
you to exit the loop based on a condition that is checked within the loop. When the
condition is met, the break statement is encountered, and the loop immediately
terminates, even if the loop's iteration limit has not been reached.

2. Early Loop Termination: The break statement provides a way to terminate the loop
before it naturally reaches its end. It allows you to exit the loop prematurely if a
certain condition arises, providing flexibility in controlling the loop's behavior.

3. Specific Event Handling: The break statement allows you to handle specific events
or conditions within a loop. When a particular event occurs, you can use the break
statement to exit the loop and move on to the next part of the program, skipping any
remaining iterations of the loop.
Example for the break statement.

# use of the break statement


i = 0
while i < 10:
if i == 5:
break
print(i)
i += 1
# output:
0
1
2
3
4

Searching for a Target Value in a List


# List of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Target value to find
target = 6
# Variable to track if the target value is found
found = False
# Index variable to iterate through the list
index = 0
# Loop through the list and check each element
while index < len(numbers):
# If the current element matches the target value
if numbers[index] == target:
# Set found to True
found = True
break # Exit the loop
index += 1 # Increment the index to move to the next element
# Check if the target value was found
if found:
print("Target found at index", index) # Print the index where the
target value was found
else:
print("Target not found in the list.") # Print a message
indicating the target value was not found
# output: Target found at index 5

• continue statement: The continue statement is used to skip over certain iterations of a
while loop based on a certain condition.

Syntax:-

while condition:
# code block

if condition:
continue

# code block

while: The keyword used to declare a while loop.

condition: The condition that is evaluated for each iteration. If the condition is True, the loop
continues; otherwise, it exits.

continue: The keyword used to indicate that the remaining code within the loop body should be
skipped, and the next iteration should begin.

i = 0
while i < 10:
i += 1
if i % 2 == 0:
continue
print(i)
# output:
1
3
5
7
9

Printing prime numbers less than 20:

# Starting number
number = 2
# Upper limit
limit = 20
while number < limit:
# Assume number is prime initially
is_prime = True

if number <= 1:
# Skip numbers less than or equal to 1
number += 1
continue
for i in range(2, number):
# Number is divisible by another number
if number % i == 0:
is_prime = False
break
if is_prime:
print(number, "is prime")
number += 1
# output:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime

Nested While loop:


A nested while loop is a loop construct that consists of one while loop nested inside another
while loop. This creates a hierarchical structure where the inner while loop is completely
contained within the outer while loop. Each iteration of the outer while loop triggers a series of
iterations of the inner while loop. The syntax of a nested while loop in Python is as follows:
# Basic syntax of nested while loop:
while condition_outer:
# Code block for the outer while loop
while condition_inner:
# Code block for the inner while loop
# Code block after the inner while loop

Conditions of While Nested Loop: In the nested while loop, there are two conditions:
condition_outer for the outer loop and condition_inner for the inner loop. The code within the
outer while loop is executed repeatedly as long as condition_outer is true. Inside the outer loop,
the inner while loop is executed repeatedly as long as condition_inner is true. The flow of
execution progresses from the outer loop to the inner loop, and then back to the outer loop,
until the conditions of both loops are no longer true.

• Outer loop:
– while keyword: It declares the outer loop.
• Outer loop condition: A condition that determines whether the outer loop
should continue or exit.
• Inner loop:
– while keyword: It declares the inner loop.
– Inner loop condition: A condition that determines whether the inner loop should
continue or exit.
• Loop body: The code block inside the inner loop that gets executed repeatedly until
the inner loop condition evaluates to False.

• Control flow: The control flow of the nested while loop is managed by the outer and
inner loop conditions. The outer loop condition is checked first, and if it is True, the
inner loop is executed. The inner loop continues until its condition becomes False.
Then, the control goes back to the outer loop, and the process repeats.

i = 1
while i <= 3:
j = 1
while j <= 3:
print(i, j)
j += 1
i += 1
# output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

• Pattern Printing using the while loop


# Example: Printing a pattern using nested while loops
row = 1
n = 5
while row <= n:
column = 1
while column <= row:
print(column, end=" ")
column += 1
print()
row += 1

# Output:-
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

• Printing a multiplication table using nested while loops


# Example: Printing a multiplication table using nested while loops
row = 1
n = 5
while row <= n:
column = 1
while column <= n:
product = row * column
print(f"{row} x {column} = {product}")
column += 1
print()
row += 1

# output:-
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25

Real life application of Nested while Loop:

1. Game Development: In game development, nested while loops can be used for
creating game levels, enemy movements, or collision detection systems. For
instance, you can have an outer loop that iterates through game levels and an inner
loop that handles the movements and interactions within each level.

2. Simulation and Modeling: When simulating real-world systems or modeling


complex phenomena, nested while loops can be utilized. For example, in a weather
simulation, an outer loop may represent the passage of time, while an inner loop
handles the simulation of weather patterns within each time step.

3. Robotics and Automation: In robotics and automation systems, nested while loops
can be used for controlling robot movements, coordinating sensors and actuators, or
executing sequences of actions. The outer loop may handle high-level task
execution, while the inner loop manages low-level sensor readings and feedback
control.

A Short Program: Rock, Paper, Scissors


• Let’s use the programming concepts we’ve learned so far to create a simple rock, paper,
scissors game.
import random, sys

print('ROCK, PAPER, SCISSORS')

# These variables keep track of the number of wins, losses, and ties.
wins = 0
losses = 0
ties = 0

while True: # The main game loop.


print('%s Wins, %s Losses, %s Ties' % (wins, losses, ties))
while True:# The player input loop.
print('Enter your move: (r)ock (p)aper (s)cissors or (q)uit')
playerMove = input()
if playerMove == 'q':
sys.exit() # Quit the program.
if playerMove == 'r' or playerMove == 'p' or playerMove == 's':
break # Break out of the player input loop.
print('Type one of r, p, s, or q.')

# Display what the player chose:


if playerMove == 'r':
print('ROCK versus...')
elif playerMove == 'p':
print('PAPER versus...')
elif playerMove == 's':
print('SCISSORS versus...')

# Display what the computer chose:


randomNumber = random.randint(1, 3)
if randomNumber == 1:
computerMove = 'r'
print('ROCK')
elif randomNumber == 2:
computerMove = 'p'
print('PAPER')
elif randomNumber == 3:
computerMove = 's'
print('SCISSORS')

# Display and record the win/loss/tie:


if playerMove == computerMove:
print('It is a tie!')
ties = ties + 1
elif playerMove == 'r' and computerMove == 's':
print('You win!')
wins = wins + 1
elif playerMove == 'p' and computerMove == 'r':
print('You win!')
wins = wins + 1
elif playerMove == 's' and computerMove == 'p':
print('You win!')
wins = wins + 1
elif playerMove == 'r' and computerMove == 'p':
print('You lose!')
losses = losses + 1
elif playerMove == 'p' and computerMove == 's':
print('You lose!')
losses = losses + 1
elif playerMove == 's' and computerMove == 'r':
print('You lose!')
losses = losses + 1

# Output: Rock, PAPER, SCISSORS


# 0 Wins, 0 Losses, 0 Ties
# Enter your move: (r)ock (p)aper (s)cissors or (q)uit
# P
# PAPER versus...
# PAPER
# It is a tie!
# 0 Wins, 1 Loses, 1 Ties
# Enter your move: (r)ock (p)aper (s)cissors or (q)uit
# s
# SCISSORS versus...
# PAPER
# You win!
# 1 Wins, 1 Losses, 1 Ties
# Enter your move: (r)ock (p)aper (s)cissors or (q)uit
# q

#Summary: By using expressions that evaluate to True or False (also called conditions), you can
write programs that make decisions on what code to execute and what code to skip.You can also
execute code over and over again in a loop while a certain condition evaluates to True . The break
and continue statements are useful if you need to exit a loop or jump back to the loop’s start.

#Key Takeaways

• This chapter has provided an introduction to Python Control flow statement and Loops
its relevance in the field of python & data science. Conditional statements in Python
allow you to execute different blocks of code based on certain conditions.They enable
your programs to make decisions and perform actions based on input or specific
conditions.Conditional statements are an essential programming concept for creating
flexible and powerful programs.

• Furthermore, this chapter has Conditional statements are important because they
allow your programs to respond dynamically to different conditions. They enable you
to automate decision-making processes based on user input or changing data
conditions.Conditional statements make your code more flexible, responsive, and
powerful.

• The chapter has also covered Loops are used to repeat a block of code multiple
times.The for loop allows you to iterate over a sequence of items and execute a block of
code for each item.The while loop allows you to execute a block of code repeatedly as
long as a certain condition is true.
• Finally, the chapter has provided a summary of the topics covered in the class.
Understanding conditional statements and loops is essential for writing dynamic and
interactive programs in Python.

• Overall, this chapter has provided a solid foundation for understanding control flow
statements and its methods in the field of python & data science. Understanding the
Python control statement and Loops in Python is essential for any data science
professional.

You might also like