Thursday, 29 May 2025

Unit 2: Control Statements in Python

 

Unit 2: Control Statements in Python                                  [8]   

2.1 if statement

2.2 match statement

2.3 break statement

2.4 continue statement

2.5 Loop statement

2.5.1 while

2.5.2 for

2.6 Nested loop

2.7 Infinite loop

Practical Works

       Write program to apply if, match, break and continue statements for decision making.

       Write program to utilize different loop statements to solve meaningful problems.

       Write program to demonstrate input validation using loop.

       Write program to create different patterns using nested loop.

       Write program to make use of infinite loop.

 

Control Statements in Python :

Control statements are designed to serve the purpose of modifying a loop's execution from its default behaviour. Based on a condition, control statements are applied to alter how the loop executes. In this tutorial, we are covering every type of control statement that exists in Python.                                   

2.1 if statement

The if statement is arguably the most used statement to control loops. For instance:

Code

# Python program to show how if statements control loops  

n = 5  

for i in range(n):  

    if i < 2:  

        i += 1  

    if i > 2:  

        i -= 2  

    print(i)  

Output:

1

2

2

1

2

 

2.2 match statement

If the condition is met, the pass statement, or a null operator, is used by the coder to leave it as it is. Python's pass control statement changes nothing and moves on to the following iteration without stopping the execution or skipping any steps after completing the current iteration.

A coder can put the pass statement to prevent the interpreter from throwing an error when a loop or a code block is left empty.

Code

# Python program to show how to create empty code blocks using a pass statement  

for l in 'Python':  

    if l == 't':  

        pass  

    print('Letter: ', l)  

Output:

Letter:  P

Letter:  y

Letter:  t

Letter:  h

Letter:  o

Letter:  n

Even if the condition was satisfied in the code above, as we can see, the pass statement had no effect, and execution went on to the subsequent iteration.

 

2.3 break statement

In Python, the break statement is employed to end or remove the control from the loop that contains the statement. It is used to end nested loops (a loop inside another loop), which are shared with both types of Python loops. The inner loop is completed, and control is transferred to the following statement of the outside loop.

Code

# Python program to show how to control the flow of loops with the break statement  

  

Details = [[19, 'Itika', 'Jaipur'], [16, 'Aman', 'Bihar']]  

for candidate in Details:  

    age = candidate[0]  

    if age <= 18:  

        break  

    print (f"{candidate[1]} of state {candidate[2]} is eligible to vote")  

Output:

Itika of state Jaipur is eligible to vote

In the above code, if a candidate's age is less than or equal to 18, the interpreter won't generate the statement of eligibility. Otherwise, the interpreter will print a message mentioning that the candidate is eligible to vote in the console.

 

2.4 continue statement

When a Python interpreter sees a continue statement, it skips the present iteration's execution if the condition is satisfied. If the condition is not satisfied, it allows the implementation of the current iteration. It is employed to keep the program running even when it meets a break while being executed.

Code

# Python program to show how to control the flow of a loop using a continue statement  

# Printing only the letters of the string  

for l in 'I am a coder':  

    if l == ' ':  

        continue  

    print ('Letter: ', l)  

Output:

Letter:  I

Letter:  a

Letter:  m

Letter:  a

Letter:  c

Letter:  o

Letter:  d

Letter:  e

Letter:  r

In this code, when the if-statement encounters a space, the loop will continue to the following letter without printing the space.

2.5 Loop statement

Statements used to control loops and change the course of iteration are called control statements. All the objects produced within the local scope of the loop are deleted when execution is completed.

2.5.1 while

While loops are used in Python to iterate until a specified condition is met. However, the statement in the program that follows the while loop is executed once the condition changes to false.

Syntax of the while loop is:

while <condition>:  

    { code block }  

All the coding statements that follow a structural command define a code block. These statements are intended with the same number of spaces. Python groups statements together with indentation.
Code

# Python program to show how to use a while loop  

counter = 0  

# Initiating the loop  

while counter < 10: # giving the condition  

    counter = counter + 3  

    print("Python Loops")  

Output:

Python Loops

Python Loops

Python Loops

Python Loops

 

2.5.2 for

Python for loop is designed to repeatedly execute a code block while iterating through a list, tuple, dictionary, or other iterable objects of Python. The process of traversing a sequence is known as iteration.

Syntax of the for Loop

for value in sequence:  

    { code block }  

In this case, the variable value is used to hold the value of every item present in the sequence before the iteration begins until this particular iteration is completed.

Loop iterates until the final item of the sequence are reached.

Code

# Python program to show how the for loop works  

 

# Creating a sequence which is a tuple of numbers  

numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]  

  

# variable to store the square of the number  

square = 0  

  

# Creating an empty list  

squares = []  

  

# Creating a for loop  

for value in numbers:  

    square = value ** 2  

    squares.append(square)  

print("The list of squares is", squares)  

Output:

The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]

 

2.6.  Nested loop

Nested loops mean loops inside a loop. For example, while loop inside the for loop, for loop inside the for loop, etc.

Python Nested Loops

Python Nested Loops

Python Nested Loops Syntax:

Outer_loop Expression:

    Inner_loop Expression:

        Statement inside inner_loop

    Statement inside Outer_loop

Python Nested Loops Examples

x = [1, 2]

y = [4, 5]

 

for i in x:

  for j in y:

    print(i, j)

Output:

14
15
24
2 5

2.7. infinite loop

If we want a block of code to execute infinite number of time, we can use the while loop in Python to do so.

The code uses a ‘while' loop with the condition (count == 0). This loop will only run as long as count is equal to 0. Since count is initially set to 0, the loop will execute indefinitely because the condition is always true.

count = 0

while (count == 0):

    print("Hello Geek")

Note: It is suggested not to use this type of loop as it is a never-ending infinite loop where the condition is always true and you have to forcefully terminate the compiler.

 

No comments:

Post a Comment

Unit IV: Evaluation and Feedback | Teaching Method | Notes | Seven Semester | BICTE

📘 Unit IV: Evaluation and Feedback Total Time: 4 Hours 🔹 4.1 Assessing Student Performance with ICT ICT tools offer flexible, efficie...