Control Flow Statement
Control Flow Statement
Control Flow Statement
In this class we will discuss about Python Conditional Statements and Loops:
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.
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.
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.")
```
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.
• 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.
Syntax:
• 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.
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.
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.
• 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.
# Output:
apple
banana
cherry
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.
Syntax:
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.
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.
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:
• 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
Syntax:
• 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
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'}
]
# 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:
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.
# 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.
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. 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.
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
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.
• 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
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
# 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
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
# Output:-
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
# 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
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.
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.
# These variables keep track of the number of wins, losses, and ties.
wins = 0
losses = 0
ties = 0
#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.