Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views20 pages

Control Statement

Chapter 5 introduces control statements in Python, which are essential for managing program execution flow through decision-making and looping. It covers the importance of control statements, including conditional and looping constructs, and provides practical examples to illustrate their usage. Understanding these concepts is crucial for writing efficient and adaptable Python code.

Uploaded by

55 Sana
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)
4 views20 pages

Control Statement

Chapter 5 introduces control statements in Python, which are essential for managing program execution flow through decision-making and looping. It covers the importance of control statements, including conditional and looping constructs, and provides practical examples to illustrate their usage. Understanding these concepts is crucial for writing efficient and adaptable Python code.

Uploaded by

55 Sana
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/ 20

Chapter: 5

5.1 Introduction to Control Statements


In the Introduction to Control Statements, readers explore core programming constructs
essential for managing a program's execution flow. Control statements facilitate decision-
making and looping, enabling the creation of dynamic, adaptable code. Through clear
explanations and practical examples, this section highlights the importance and use of control
statements in Python. It provides a foundation for understanding conditional and iterative logic,
preparing readers for advanced topics. By clarifying the syntax and purpose of control
statements, readers develop the skills needed to write logical and efficient Python code for
various programming challenges.
5.1.1 What are Control Statements?
Control statements are fundamental constructs in programming languages like Python,
facilitating the alteration of program execution flow based on certain conditions or loops. They
allow programmers to dictate which parts of the code should be executed and under what
circumstances. Essentially, control statements enable decision-making and looping within
programs, providing the ability to create dynamic and responsive code. In Python, common
control statements include conditional statements (e.g., if, elif, else) for decision-making and
looping statements (e.g., while, for) for iteration. Understanding control statements is crucial
for mastering the flow of program execution and creating efficient and flexible code structures.
Control statements alter the normal sequential flow of execution in a program.
They allow for decision-making, looping, and altering the flow of code based on conditions.
Control structures enable more dynamic and responsive programs that can adapt to inputs and
conditions.
5.1.2 Importance and Usage in Programming
Here are some advantages of control statements in programming:
1. Logic Flow Control: Control statements allow programmers to direct the flow of logic
within a program, determining which code blocks execute based on conditions or loops.
2. Decision Making: They enable decision-making within programs by evaluating
conditions and executing specific blocks of code accordingly, providing flexibility and
adaptability.
3. Repetitive Tasks Automation: Control statements, especially looping constructs,
automate repetitive tasks by executing a block of code iteratively, reducing redundancy
and enhancing efficiency.
4. Dynamic Program Behavior: With control statements, programmers can create
dynamic program behavior, where the program's actions can vary based on input,
external factors, or changing conditions during runtime.
5. Complex Program Behavior: They facilitate the implementation of complex program
behavior, such as branching, nesting, and looping, allowing for the development of
sophisticated algorithms and applications.
6. Error Handling: Control statements play a crucial role in error handling and exception
management by providing mechanisms to handle unexpected conditions and recover
from errors gracefully.
7. Readable and Maintainable Code: Proper use of control statements enhances code
readability and maintainability by organizing logic into structured blocks, making it
easier for developers to understand, modify, and debug code.
8. Efficient Resource Utilization: By controlling the execution flow and optimizing
looping structures, control statements contribute to efficient resource utilization,
improving program performance and scalability.
9. Conditional Execution: They enable conditional execution of code, where certain
actions are performed only when specific conditions are met, leading to more efficient
and concise program design.
10. Enhanced Control: Control statements offer programmers enhanced control over
program behavior, allowing for precise manipulation of program execution based on
varying conditions and requirements.
5.2 Conditional Statements
Conditional statements are programming constructs that enable the execution of different code
blocks based on specific conditions. They allow programmers to create decision-making
structures within their code, where certain actions are taken if a condition is true and alternative
actions are taken if the condition is false. The fundamental purpose of conditional statements
is to add flexibility and adaptability to programs, allowing them to respond dynamically to
different inputs or situations.
Conditional statements enable logical branching in programs, allowing them to choose
different execution paths based on conditions. This capability is crucial for creating responsive
software that can intelligently adapt to various scenarios, such as displaying different forecasts
in a weather application based on current conditions.
5.2.1 if Statement
The if statement in Python is used to execute a block of code if a specified condition
evaluates to true.
Syntax
if condition
# code block to execute if condition is True
Explanation
condition: This is the expression that is evaluated. If the condition evaluates to True, the code
block following the if statement is executed. If the condition evaluates to False, the code block
is skipped.
Code block: It consists of one or more statements that are indented and executed if the
condition is True. If the condition is False, the code block is ignored.
Example
x = 10
if x > 5:
print("x is greater than 5")
The condition x > 5 evaluates to True because the value of x is 10, which is greater than 5.
Therefore, the code block print("x is greater than 5") is executed, and the output will be:
x is greater than 5
Single if
The single if statement in Python is used to execute a block of code if a specified condition
evaluates to true.
Syntax
if condition:
# code block to execute if condition is True
Explanation
condition: This is the expression that is evaluated. If the condition evaluates to True, the code
block following the if statement is executed. If the condition evaluates to False, the code block
is skipped.
Code block: It consists of one or more statements that are indented and executed if the
condition is True. If the condition is False, the code block is ignored.
Example
age = 20
if age >= 18:
print("You are an adult.")
Explanation
The condition age >= 18 evaluates to True because the value of age is 20, which is greater than
or equal to 18.
Therefore, the code block print("You are an adult.") is executed.
The output will be
You are an adult.
If the value of age were, for example, 15, the condition would evaluate to False, and the code
block would not be executed.
Multiple if statements
Multiple if statements in Python allow for the execution of different code blocks based on
multiple conditions. Each if statement is evaluated independently, regardless of the evaluation
of previous if statements. Here's an explanation
Syntax
if condition1:
# code block to execute if condition1 is True
if condition2:
# code block to execute if condition2 is True
# Additional if statements as needed...
Explanation
Each if statement begins with the keyword if, followed by a condition that is evaluated. If the
condition associated with an if statement evaluates to True, the corresponding code block is
executed. Each if statement is evaluated independently. Even if a code block is executed due
to a True condition in a previous if statement, subsequent if statements are still evaluated.
Example
x = 15%2=1
if x > 10:
print("x is greater than 10")
if x % 2 == 0:
print("x is even")
Explanation
The condition x > 10 evaluates to True because the value of x is 15, which is greater than 10.
Therefore, the code block print("x is greater than 10") is executed. The condition x % 2 == 0
evaluates to False because 15 is not divisible by 2. Therefore, the code block associated with
this if statement is not executed. This illustrates how multiple if statements can lead to the
execution of different code blocks based on the evaluation of independent conditions.
Chained if statements
Chained if statements, also known as if...elif...else statements, allow for the evaluation of
multiple conditions sequentially. The elif (short for "else if") keyword is used to specify
additional conditions to check if the previous conditions were not true. Here's an explanation:
Syntax
x = 15
if x > 20:
print("x is greater than 20")
elif x > 10:
print("x is greater than 10 but less than or equal to 20")
elifcondition
else:
print("x is less than or equal to 10")
Example
The condition x > 20 evaluates to False, so the code block associated with this if statement is
not executed.
The condition x > 10 evaluates to True because the value of x is 15, which is greater than 10.
Therefore, the code block print("x is greater than 10 but less than or equal to 20") is executed.
The else block is not executed because one of the if or elif conditions evaluated to True.
if...else Statement
The if...else statement in Python allows for the execution of different code blocks based on the
evaluation of a single condition. If the condition is true, the code block associated with the if
statement is executed; otherwise, the code block associated with the else statement is executed.
Syntax
if condition:
# code block to execute if condition is True
else:
# code block to execute if condition is False
Explanation
The if statement begins with the keyword if, followed by a condition that is evaluated. If the
condition is true, the corresponding code block is executed. If the condition associated with the
if statement is false, the code block associated with the else statement is executed. The else
statement is optional. If it is not provided, the program simply moves on to the next statement
after the if block.
Example
x = 15
if x > 10:
print("x is greater than 10")
else:
print("x is less than or equal to 10")
The condition x > 10 evaluates to True because the value of x is 15, which is greater than 10.
Therefore, the code block print("x is greater than 10") is executed. Since there is no else
statement, there is no alternative code block to execute if the condition is false.
Nested if...else Statement
A nested if...else statement in Python involves placing an if...else statement within another if
or else block. This allows for more complex decision-making logic, where one condition leads
to another set of conditions. Here's an explanation:
Syntax
if outer_condition:
# code block for outer condition
if inner_condition:
# code block for inner condition if outer condition is true
else:
# code block for inner condition if outer condition is true
else:
# code block if outer condition is false
Explanation
The outer if statement begins with the keyword if, followed by a condition that is evaluated. If
the outer condition is true, the code block associated with it is executed. Within the code block
of the outer if statement, there can be another if...else statement (inner if...else) or any other
code. If the outer condition is false, the code block associated with the else statement (if
provided) is executed.
x = 15
y=5
if x > 10:
print("x is greater than 10")
if y > 10:
print("y is also greater than 10")
else:
print("y is less than or equal to 10")
else:
print("x is less than or equal to 10")
The outer condition x > 10 evaluates to True because the value of x is 15, so the code block
associated with it is executed. Within the code block of the outer if statement, the inner
condition y > 10 evaluates to False because the value of y is 5, so the else block associated with
the inner if...else statement is executed.
Output
x is greater than 10
y is less than or equal to 10
5.2.2 elif Statement
The elif statement is short for "else if" and is used in Python to evaluate multiple conditions
sequentially after an initial if statement. It provides an alternative condition to check if the
previous conditions were not true. Here's an explanation
Syntax
if condition1:
# code block to execute if condition1 is True
elif condition2:
# code block to execute if condition2 is True
elif condition3:
# code block to execute if condition3 is True
# Additional elif statements as needed...
Explanation
The if statement begins with the keyword if, followed by a condition that is evaluated. If the
condition is true, the corresponding code block is executed.
If the condition associated with the if statement is false, the elif statement is evaluated.
Each elif statement is evaluated sequentially until a true condition is encountered. When a true
condition is found, the corresponding code block is executed, and the rest of the elif statements
are skipped.
The elif statement is optional. If it is not provided, the program simply moves on to the next
statement after the if block.
Example
x = 15
if x > 20:
print("x is greater than 20")
elif x > 10:
print("x is greater than 10 but less than or equal to 20")
else:
print("x is less than or equal to 10")
Example:
# Program to assign grades based on a score
score = int(input("Enter your score: "))
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
5.2.3 else Statement
The else statement in Python is used in conjunction with an if statement to execute a block of
code if the condition of the if statement evaluates to false. It provides an alternative action to
take when none of the preceding conditions are true. Here's an explanation:
Syntax
if condition:
# code block to execute if condition is True
else:
# code block to execute if condition is False
Example
x=5
if x > 10:
print("x is greater than 10")
else:
print("x is less than or equal to 10")
5.3 Looping Statements
In "Looping Statements," programming constructs enable repetitive execution of code blocks.
Key looping mechanisms like while and for loops facilitate iteration over data structures or
until specific conditions are met. while loops iterate as long as a condition holds true, allowing
dynamic control over loop termination. for loops offer a convenient syntax for iterating over
sequences like lists or strings, simplifying repetitive tasks. Understanding looping statements
empowers programmers to efficiently process data, automate tasks, and implement complex
algorithms. Through concise explanations and practical examples, this section equips readers
with essential skills for harnessing the power of iteration in Python programming.
Loops
Statement based on the condition, Multiple time condition check, so we execute multiple
statement. No. of Lines reduces
A statement is executed only once from top to bottom.
Loops are used when we want to execute a part of the program or a block of statements several
times. With the help of loop, we can execute a part of the program repeatedly till some condition
is true.
There are four types of loop statements in python.
• While loop
• An Infinite Loop
• The else statement for while loop
• Single Statement while
• For loop
• Nested for loop
• Loop control statements
5.3.1 while Loop
A while loop in python iterates till its condition becomes False. In other words, it executes the
statements under itself while the condition it takes is true.
When the program control reaches the while loop, the condition is checked. If the condition is
true, the block of code under it is executed. Remember to indent all statements under the loop
equally. After that, the condition is checked again. This continues until the condition becomes
false. Then, the first statement, if any, after the loop is executed.
The while loop in Python repeatedly executes a block of code as long as a specified
condition is true.
Syntax
while condition:
# code block to execute while condition is True
Explanation
condition: This is the expression that is evaluated before each iteration of the loop. If the
condition is true, the code block inside the loop is executed. If the condition is false, the loop
terminates.
Code block: It consists of one or more statements that are indented and executed repeatedly as
long as the condition remains true.
Example
count = 0
while count < 5:
print("Count:", count)
count += 1
Output
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
Example: # This loop calculates the sum of numbers from 1 to 10
total = 0
num = 1
while num <= 10:
total += num
num += 1
print("The sum is:", total)
An Infinite Loop
An infinite loop occurs when the condition in a while loop never evaluates to False. This causes
the loop to run indefinitely unless interrupted. It can be useful in certain applications, like
continuously checking for input or running a server.
Example
while True:
print ("This will run forever unless stopped.")
Here, the condition True is always met, so the loop will run infinitely unless it is manually
stopped, such as using a break statement or an external interrupt (e.g., Ctrl+C).
Causes of Infinite Loops
• Incorrect Loop Condition: If the condition specified in the loop's control structure
(e.g., while or for loop) is always true, the loop will continue indefinitely.
• Improper Use of Loop Control Statements: Incorrect use of loop control statements
like break or continue may result in the loop never terminating as expected.
Example
count = 0
while True:
if count == 5:
break # This break statement is missing a condition, leading to an infinite loop
print(count)
count += 1
The Else Statement for While Loop
Python allows the use of an else clause with a while loop. The code inside the else block is
executed only when the while loop completes naturally without encountering a break statement.
Syntax:
while condition:
# code block
else:
# code block if loop completes without break
Example:
count = 0
while count < 5:
print(count)
count += 1
else:
print("Loop completed successfully.")
In this case, once the loop finishes iterating, the else block will execute, printing "Loop
completed successfully."
Single Statement While
In Python, you can write a while loop with a single statement on the same line. This is more of
a shorthand technique for writing concise loops.
Syntax:
while condition: statement
Example
count = 0
while count < 5: print(count); count += 1
This is functionally the same as a normal while loop but condensed into one line.
For Loop
A for loop is used to iterate over a sequence (such as a list, tuple, string, or range). It is
preferred when the number of iterations is known or when iterating over items in a collection.
Syntax
for item in sequence:
# code block to execute for each item in the sequence
Explanation
item: This is a variable that takes on the value of each item in the iterable, one at a time, during
each iteration of the loop.
sequence: This is a sequence or any object that can be iterated over. It could be a list, tuple,
string, range, or any other iterable object.
Code block: It consists of one or more statements that are indented and executed for each item
in the iterable.
1. Iterating Over a Range
Example
for num in range(5):
print(num)
In this example, the for loop iterates over the range of numbers from 0 to 4 and prints each
number.
2. Iterating Over a List
Example
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output
apple
banana
cherry
3. Iterating Over a String
Example
word = "Python"
for letter in word:
print(letter)
4. Using break in a For Loop
Example:
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
for fruit in fruits:
print(fruit)
if fruit == "cherry":
break
Output
apple
banana
cherry
5. Using continue in a For Loop
Example:
for i in range(10):
if i % 2 == 0:
continue
print(i)
6. Iterating Over a Dictionary
Example
student_scores = {"Alice": 90, "Bob": 85, "Charlie": 95}
for student, score in student_scores.items():
print(f"{student}: {score}")
7. Using else with a For Loop
Example
for i in range(3):
print(i)
else:
print("Loop completed successfully")
8. For Loop with Conditional Statements
Example
numbers = range(10)
for num in numbers:
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
9. Calculating the Sum of a List
Example
numbers = [1, 2, 3, 4, 5]
total = 0
for number in numbers:
total += number
print("Sum:", total)
10. Iterating Over a Tuple
Example
colors = ("red", "green", "blue")
for color in colors:
print(color)
11. Using range with a Step
Example
for i in range(0, 10, 2):
print(i)
12. Calculating Factorials Using a For Loop
Example
n=5
factorial = 1
for i in range(1, n + 1):
factorial *= i
print(f"The factorial of {n} is {factorial}")
13. Simulating a Do-While Loop
Example
numbers = [1, 2, 3]
while True:
for num in numbers:
print(num)
if some_condition:
break
14. Using else in a Search Loop
Example
numbers = [1, 3, 5, 7]
for num in numbers:
if num == 4:
print("Found number 4!")
break
else:
print("Number 4 not found.")
Example: pass
for letter in "hello":
if letter == "l":
pass
else:
print(letter)
These examples demonstrate how loop control statements provide flexibility in controlling the
flow of loops, allowing for customized behaviour and efficient iteration over sequences.
15. Nested For Loops
A nested for loop is when one for loop is placed inside another for loop. It is useful for working
with multi-dimensional data structures like matrices or lists of lists.
Syntax
for outer_item in outer_iterable: # Outer loop
for inner_item in inner_iterable: # Inner loop
# code block to execute for each combination of outer_item and inner_item
The outer loop iterates over the elements of an outer iterable object.
For each iteration of the outer loop, the inner loop iterates over the elements of an inner
iterable object.
The code block inside the inner loop is executed for each combination of elements from the
outer and inner iterables.
This process continues until all combinations have been processed.
Example
for i in range(3):
for j in range(2):
print(i, j)
Output
00
01
10
11
20
21
In this case, the outer loop runs three times, and for each iteration of the outer loop, the inner
loop runs twice.
Nested loops are commonly used in scenarios where operations need to be performed on
combinations of elements from multiple iterables or in situations requiring multi-level iteration
over data structures like matrices or nested lists. They provide a powerful mechanism for
handling complex repetitive tasks in Python programming.
5.3.2 Loop Control Statements
Loop control statements alter the flow of execution in loops. Python provides three control
statements: break, continue, and pass.
5.3.2.1 break Statement
The break statement is used to exit the loop prematurely, regardless of whether the loop
condition is still true or not. It is typically used when a specific condition is met, and there is
no need to continue iterating. When break is encountered inside a loop, the control flow
immediately exits the loop, and the program continues with the statement immediately
following the loop.
Terminates the loop entirely and transfers control to the statement following the loop.
Example
for i in range(5):
if i == 3:
break
print(i)
Output
0
1
2
Explanation
The range(5) function generates a sequence of numbers starting from 0 up to, but not including,
5. So, it produces the sequence: 0, 1, 2, 3, 4. for i in range(5) initiates a for loop that iterates
over each number in the range generated above. The variable i will take on the values 0, 1, 2,
3, 4 one at a time in each iteration. Inside the loop, there's an if statement that checks if the
current value of i is equal to 3. If the condition i == 3 is True, the break statement is executed,
which immediately stops the loop, and no further iterations occur. If the condition i == 3 is
False, the loop continues and the current value of i is printed.
5.3.2.2 continue Statement
The continue statement is used to skip the rest of the code block inside the loop for the current
iteration and proceed to the next iteration. It is typically used when you want to skip certain
iterations based on a specific condition without terminating the entire loop.
Example
for i in range(5):
if i == 2:
continue
print(i)
Explanation
Inside the loop, there's an if statement that checks if the current value of i is equal to 2.
If the condition i == 2 is True, the continue statement is executed. This causes the loop to skip
the current iteration and move directly to the next one without executing any further code in
that iteration (i.e., print(i) is skipped when i equals 2). If the condition i == 2 is False, the loop
continues normally, and the current value of i is printed.
Output
0
1
3
4
5.3.2.3 pass Statement
A null statement that allows the loop to continue without executing any code. It is used when
a statement is syntactically required but no action is needed.
Example
for num in range(10):
if num % 2 == 0:
pass # Placeholder for future code
else:
print(num)
Example
for i in range(5):
if i == 2:
pass
else:
print(i)
Example
for i in range(5):
if i == 2:
pass
else:
print(i)
Example
for i in range(5):
if i == 2:
pass
else:
print(i)
Pass statement vs comment
You may be wondering that a python comment works similar to the pass statement as it does
nothing so we can use comment in place of pass statement. Well, it is not the case, a comment
is not a placeholder and it is completely ignored by the Python interpreter while on the other
hand pass is not ignored by interpreter, it says the interpreter to do nothing.
Python pass statement example
If the number is even, we are doing nothing and if it is odd then we are displaying the
number.
for a in [20, 19, 9, 66, 6, 91, 24]:
if a%2 == 0:
pass
else:
print(a)
The pass statement is a null operation that does nothing when executed. It is often used as a
placeholder when a statement is syntactically required but no action is needed. It is commonly
used to create empty code blocks that will be filled in later.
Looping with conditions provides a powerful mechanism for executing code repetitively while
maintaining flexibility and adaptability based on changing conditions during program
execution.
Match Statement (Python 3.10+)
A control statement for pattern matching, similar to a switch-case statement in other languages.
It simplifies complex if-elif chains by matching values or data patterns.
Example:
status_code = 200
match status_code:
case 200:
print("OK")
case 404:
print("Not Found")
case _:
print("Unknown status")
These control statements are essential for creating efficient, logical, and well-structured Python
programs. Understanding these different loop types and control statements is crucial for writing
efficient Python code. They allow developers to handle repeated tasks, control complex flows,
and work with multi-dimensional data, making Python a powerful tool for programming tasks.

Program
Program to check if a number is even or odd
Program to check if a person is eligible to vote
Program to check if a year is a leap year
Program to check if a number is positive, negative, or zero
Program using while loop calculates the factorial of a number
Program calculates the sum of numbers from 1 to n using a for loop.
Program prints numbers from 1 to 5 using a while loop.
Program breaks out of the loop when i equals 5.
Program skips the iteration when i equals 3 and continues the loop.

You might also like