SOLVED: How to loop n times in Python [10 Easy Examples]

How to loop n number of times in Python

Python provides two different types of looping statements. Here, while loop is  similar to the other programming language like C/C++ and Java. Whereas, the for loop is used for two purpose. First one is to iterate over the sequence like List, Tuple, Set and Dictionary. And the other one is to iterate over the range of numbers.

 

Using python for loop

This version of for loop will iterate over a sequence of numbers using the range() function. The range() represents an immutable sequence of numbers and is mainly used for looping a specific number of times in for loops. Note that the given end point in the range() is never part of the generated sequence. When you want to access the position along with the values of a sequence, this version of for loop is used.

Advertisement

 

Syntax

The syntax of for loop is as shown below.

for iterator in range(start, stop, step):
     block of statements
else:
     block of statements

Or


for iterator in sequence:
     block of statements
else:
     block of statements

 

Example 1 - Using range function to loop n times

The example here iterates over the range of numbers from 1 to 10 and prints its value. However, if it reaches the number divisible by 5, it will break the loop. Note that in this case, the statement inside the else block will not be printed as the loop stops iterating when the value reaches 5.

for i in range(1, 10):
    if(i%5==0):
        break
    print(i)
else:
    print("This statement gets printed only if the for loop terminates after iterating for given number of times and not because of break statement")

Output

1
2
3
4

 

Example 2 - Iterating over list elements using range() function

When you want to iterate over the sequence one way is to iterate using the for loop given below that gives the position of the desired element. The example below iterates over the list of fruits and returns the position of fruit "Mango".

fruits = ["Apple", "Mango", "Banana", "Pineapple", "Strawberry"]
for i in range(0, len(fruits)):
    if(fruits[i]=="Mango"):
        print("Mango found at position ",(i+1))
        break
    i+=1

Output

Advertisement
Mango found at position 2


Example 3 - Iterating over list elements without range() function

However, if you just want to operate on the value of the sequence without considering its corresponding position in the sequence, you can use the for loop given below.


fruits = ["Apple", "Mango", "Banana", "Pineapple", "Strawberry"]
for i in fruits:
    if(i=="Mango"):
       print("Mango found in the list")
       break

Output

Mango found in the list

 

Example 4 - Loop n times without index variable

In all our previous examples we have used index variable to process the loop element. Now if we don't want to use the index variable then you can use the range() in following way:

num = 5
for _ in range(num):
   print("This will run n number of times the elements present in num")

Output:

This will run n number of times the elements present in num
This will run n number of times the elements present in num
This will run n number of times the elements present in num
This will run n number of times the elements present in num
This will run n number of times the elements present in num

Alternatively we can also use itertools to achieve the same, here is another example:

import itertools

num = 5
for _ in itertools.repeat(None, num):
    print(f"I will repeat myself {num} times")

Output:

Advertisement
I will repeat myself 5 times
I will repeat myself 5 times
I will repeat myself 5 times
I will repeat myself 5 times
I will repeat myself 5 times

 

Example 5 - Nested for loops 

However, if you just want to operate on the value of the sequence without considering its corresponding position in the sequence, you can use the for loop given below.

rows=5
for i in range(1, rows + 1):
    for j in range(1, i + 1):
        print(j, end=" ")
    print('')

Output

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5

 

Using python while loop

While loop is also used to iterate over the range of numbers or a sequence. The while loop executes the block until a given condition is satisfied. As soon as the condition becomes false, it will stop executing the block of statements, and the statement immediately after the loop is executed. We can also write the else clause that gets executed if and only if the loop terminates because of false condition and not because of any other exception or break statement.

Syntax

The syntax of for loop is as shown below.

Initialization
while condition:
     block of statements
     increment/decrement
else:
     block of statements

 

Example 6 - While with else block

In the example given below, we are having a counter that prints the number from 100 to 105. And, once it reaches the value, the loop terminates and else clause gets executed.

count=100
while(count<105):
     print(count)
     count +=1
else:
     print("count value reached")

Output

Advertisement
100
101
102
103
104
count value reached

 

Example 7 - Constructing Dictionary from two  list

In the example given below, We have two list containing the name of countries and name of capital respectively. Here, we will read the value from the two lists and construct the dictionary out of this lists.

l1=['India', 'Australia', 'Nepal', 'Bhutan']
l2=['Delhi', 'Canberra', 'Kathmandu', 'Thimphu']
d={}
i=0
while i<len(l1) and i<len(l2):
    d.update({l1[i]:l2[i]})
    i+=1
else:
    print("Dictionary constructed successfully")
print("Retrieving values from Dictionary")
print(d)

Output

Dictionary constructed successfully
Retrieving values from Dictionary
{'India': 'Delhi', 'Australia': 'Canberra', 'Nepal': 'Kathmandu', 'Bhutan': 'Thimphu'}

 

Example 8 - While loop inside for loop

In the example given below, we will print the multiplication table of a number till the given number.

for i in range(1, 6):
    print('Multiplication table of:', i)
    count = 1
    while count < 11:
        print(i * count, end=' ')
        count = count + 1
    print('\n')

Output

Multiplication table of: 1
1 2 3 4 5 6 7 8 9 10

Multiplication table of: 2
2 4 6 8 10 12 14 16 18 20

Multiplication table of: 3
3 6 9 12 15 18 21 24 27 30

Multiplication table of: 4
4 8 12 16 20 24 28 32 36 40

Multiplication table of: 5
5 10 15 20 25 30 35 40 45 50

 

Example 9 - Nested while loop

In the example given below, We will use two while loops that creates a tuples inside the list. Here, we are creating a tuple of two elements as iterator i multiplied by count and i+1 multiplied by count.

l=[]
i=1
while i<6:
    count=0
    while count < 2:
        t=(i*count, i+1*count)
        l.insert(i, t)
        count+=1
    print(l)

Output

Advertisement
[(0, 1), (1, 2)]
[(0, 1), (1, 2), (2, 3), (0, 2)]
[(0, 1), (1, 2), (2, 3), (3, 4), (0, 3), (0, 2)]
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (0, 4), (0, 3), (0, 2)]
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (0, 5), (0, 4), (0, 3), (0, 2)]

 

Example-10: Loop n times using while without index number

We can also loop through a range of numbers without using the index number:

num = 5
    
while num > 0:
    print(f"I will repeat myself {num} times")
    num -= 1    

Output:

I will repeat myself 5 times
I will repeat myself 4 times
I will repeat myself 3 times
I will repeat myself 2 times
I will repeat myself 1 times

 

Summary

The knowledge of looping is core to python programming language that is very useful to formulate a complex logic easily. You will frequently need to use the looping control statements to build varied of applications. The knowledge of looping in different formats and combinations helps solving the really complex task to a time efficient solution. In this tutorial, we covered the for loop and while loop with the different combinations and an example to demonstrate the functionalities of looping. All in all, this tutorial, covers everything that you need to know in order to understand and use the looping in Python.

 

References

Control Flow statement

 

Related Keywords: for loops python, python repeat number n times, python repeat string n times, while loop python, for i in range python, python repeat character n times, for i to n python, python loop n times without index, for loops python, python repeat number n times, python repeat string n times, while loop python, for i in range python, python repeat character n times

Advertisement

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X