Python Loops

The following loops are available in Python to fulfil the looping needs. Python offers 3 choices for running the loops. The basic functionality of all the techniques is the same, although the syntax and the amount of time required for checking the condition differ.

We can run a single statement or set of statements repeatedly using a loop command.

The following sorts of loops are available in the Python programming language.

Sr.No.Name of the loopLoop Type & Description
1While loopRepeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.
2For loopThis type of loop executes a code block multiple times and abbreviates the code that manages the loop variable.
3Nested loopsWe can iterate a loop inside another loop.

Loop Control Statements

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.

Python provides the following control statements. We will discuss them later in detail.

Let us quickly go over the definitions of these loop control statements.

Sr.No.Name of the control statementDescription
1Break statementThis command terminates the loop’s execution and transfers the program’s control to the statement next to the loop.
2Continue statementThis command skips the current iteration of the loop. The statements following the continue statement are not executed once the Python interpreter reaches the continue statement.
3Pass statementThe pass statement is used when a statement is syntactically necessary, but no code is to be executed.

The for Loop

Python’s 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]

Using else Statement with for Loop

As already said, a for loop executes the code block until the sequence element is reached. The statement is written right after the for loop is executed after the execution of the for loop is complete.

Only if the execution is complete does the else statement comes into play. It won’t be executed if we exit the loop or if an error is thrown.

Here is a code to better understand if-else statements.

Code

# Python program to show how if-else statements work  

  

string = "Python Loop"  

  

# Initiating a loop  

for s in a string:  

    # giving a condition in if block  

    if s == "o":  

        print("If block")  

    # if condition is not satisfied then else block will be executed  

    else:  

        print(s)

Output:P y t h If block n L If block If block p

Now similarly, using else with for loop.

Syntax:


  1. for value in sequence:  
  2.      # executes the statements until sequences are exhausted  
  3. else:  
  4.      # executes these statements when for loop is completed  
# Python program to show how to use else statement with for loop  

  

# Creating a sequence  

tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)  

  

# Initiating the loop  

for value in tuple_:  

    if value % 2 != 0:  

        print(value)  

# giving an else statement  

else:  

    print("These are the odd numbers present in the tuple")

Output:3 9 3 9 7 These are the odd numbers present in the tuple

The range() Function

With the help of the range() function, we may produce a series of numbers. range(10) will produce values between 0 and 9. (10 numbers).

We can give specific start, stop, and step size values in the manner range(start, stop, step size). If the step size is not specified, it defaults to 1.

Since it doesn’t create every value it “contains” after we construct it, the range object can be characterized as being “slow.” It does provide in, len, and __getitem__ actions, but it is not an iterator.

The example that follows will make this clear.

Code

# Python program to show the working of range() function  

  

print(range(15))  

  

print(list(range(15)))  

  

print(list(range(4, 9)))  

  

print(list(range(5, 25, 4)))

Output:range(0, 15) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] [4, 5, 6, 7, 8] [5, 9, 13, 17, 21]

To iterate through a sequence of items, we can apply the range() method in for loops. We can use indexing to iterate through the given sequence by combining it with an iterable’s len() function. Here’s an illustration.

Code

# Python program to iterate over a sequence with the help of indexing  

  

tuple_ = ("Python", "Loops", "Sequence", "Condition", "Range")  

  

# iterating over tuple_ using range() function  

for iterator in range(len(tuple_)):  

    print(tuple_[iterator].upper())

Output:PYTHON LOOPS SEQUENCE CONDITION RANGE

While Loop

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

Using else Statement with while Loops

As discussed earlier in the for loop section, we can use the else statement with the while loop also. It has the same syntax.

Code

#Python program to show how to use else statement with the while loop  

counter = 0  

  

# Iterating through the while loop  

while (counter < 10):      

    counter = counter + 3  

    print("Python Loops") # Executed untile condition is met  

# Once the condition of while loop gives False this statement will be executed  

else:  

    print("Code block inside the else statement")

Output:Python Loops Python Loops Python Loops Python Loops Code block inside the else statement

Single statement while Block

The loop can be declared in a single statement, as seen below. This is similar to the if-else block, where we can write the code block in a single line.

Code

# Python program to show how to write a single statement while loop  

counter = 0  

while (count < 3): print("Python Loops")

Loop Control Statements

Now we will discuss the loop control statements in detail. We will see an example of each control statement.

Continue Statement

It returns the control to the beginning of the loop.

Code

# Python program to show how the continue statement works  

  

# Initiating the loop  

for string in "Python Loops":  

    if string == "o" or string == "p" or string == "t":  

         continue  

    print('Current Letter:', string)

Output:Current Letter: P Current Letter: y Current Letter: h Current Letter: n Current Letter: Current Letter: L Current Letter: s

Break Statement

It stops the execution of the loop when the break statement is reached.

Code

# Python program to show how the break statement works  

  

# Initiating the loop  

for string in "Python Loops":  

    if string == 'L':  

         break  

    print('Current Letter: ', string)

Output:Current Letter: P Current Letter: y Current Letter: t Current Letter: h Current Letter: o Current Letter: n Current Letter:

Pass Statement

Pass statements are used to create empty loops. Pass statement is also employed for classes, functions, and empty control statements.

Code

# Python program to show how the pass statement works  

for a string in "Python Loops":  

    pass  

print( 'Last Letter:', string)

Output:Last Letter: s

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *