Loops in Python with Examples

FREE Online Courses: Enroll Now, Thank us Later!

Generally, a loop is something that coils around itself. Loops in the programming context have a similar meaning. In this article, we will learn different types of loops in Python and discuss each of them in detail with examples. So let us begin.

Introduction to Loops in Python

In programming, the loops are the constructs that repeatedly execute a piece of code based on the conditions. These are useful in many situations like going through every element of a list, doing an operation on a range of values, etc.

There are two types of loops in Python and these are for and while loops. Both of them work by following the below steps:

1. Check the condition
2. If True, execute the body of the block under it. And update the iterator/ the value on which the condition is checked.
3. If False, come out of the loop

Working of Loops in Python

Now let us discuss each of the loop types in the following sections.

While Loop in Python

While loops execute a set of lines of code iteratively till a condition is satisfied. Once the condition results in False, it stops execution, and the part of the program after the loop starts executing.

The syntax of the while loop is :

while condition:
    statement(s)

An example of printing numbers from 1 to 5 is shown below.

Example of Python while loop:

i=1
while (i<=5):
    print(i)
    i=i+1

Output:

1
2
3
4
5

Here the condition checked is ‘i<=5’. For the first iteration, i=1 and is less than 5. So, the condition is True and 1 is printed. Then the ‘i’ value is incremented to print the next number and the condition is checked. When the value of ‘i’ becomes 6, the condition will be False and the execution of the loop stops.

1. Infinite loop in python

Infinite loop is the condition where the loop executes infinite time, that is it does not stop the execution of the while loop. This happens in two cases:

a. When we forget to increment the variable based on which the condition is checked.

For example, in the above example if we don’t increase the i with 1 after every execution. Then the condition’i<=5’ will be True every time and we continuously get the output as 1 infinitely.

b. When we give a wrong condition. In the above example again, if we give the condition as ‘i>0’. Then as the initial value is 1 and we are incrementing it. So, the condition will always be True. So we continuously get the values 1,2,3…..and so on.

What if we get to this case where we fall into an infinite loop? Then we can stop the execution manually by pressing Ctrl+C.

There are cases where the infinite loop might be useful like when we need a semaphore or for the server/client programming.

2. Else statements in Python

We would have seen the else being used along with if statement. In this case, else executes when the condition in the if statement is False.

Else is used for a similar purpose along with the while loop. The code in the else part is executed when the condition in the while gives False. This False might be at first or any other number of iteration.

The syntax for this is

while condition:
    statement(s)
else:
    statement(s)

Example on while loop with else:

while(i<=5):
    print(i)
    i=i+1
else:
    print("End of the loop")

Output:

1
2
3
4
5
End of the loop

We see that the else statement executes even after the while is executed once or more than once. But what if we want the ‘else’ part to execute only when the while does not?

In this case, we can use the break statement when the end condition is reached. Since else is a part of the while, using the break lets the code ignore the else part when reached the end condition. The below example shows this.

Example on while loop with else and statement:

i=1
while(i<=5):
    print(i)
    i=i+1
    if(i==6): break
else:
    print("This executes only when while does not loop at all")

Output:

1
2
3
4
5

But if the while loop does not execute at least one time, then the break doesn’t run and the else part will be executed. The below example shows this. Here the value of ‘i’ is 7 which is more than 5. So, the while loop will not execute at all. Because of this, the else part executes.

Example of Python while loop with else and break statement:

i=7
while(i<=5):
    print(i)
    i=i+1
    if(i==6): break
else:
    print("This executes only when while does not loop at all")

Output:

This executes only when while does not loop at all

3. Python Single statement while loop

We can write the while loop on a single statement, by writing the body after the colon (:) in the same line as the while. We can separate the multiple lines of the body by using the semicolon (;).

Example on while loop with else and break statement:

num=5
while(num>0): print(num); num=num-1

Output:

5
4
3
2
1

Python For loop

For loop in Python works on a sequence of values. For each value in the sequence, it executes the loop till it reaches the end of the sequence. The syntax for the for loop is:

for iterator in sequence:
    statement(s)

We use an iterator to go through each element of the sequence. For example, let us use for loop to print the numbers from 0 to 4.

Example of Python for loop:

for i in range(5):
    print(i)

Output:

0
1
2
3
4

We can see that though we gave the input as 5 for the range function, we got the output only till 4. This is because the range function starts from 0 and forms a sequence of values from 0 to the value one less than the argument. Here we have 0 to (5-1) i.e., 0 to 4.

To get from 1 to 5, we have two ways:

1. We can print the value of ‘i+1’ rather than ‘i’
2. We can give the sequence as the range(1,6). Giving the first argument as 1, makes the sequence start from 1. Since the end value will be 6-1= 5, we get the output till 5.

The below example shows the outputs of both cases.

Example of Python for loop:

for i in range(5):
    print(i+1)

for i in range(1,6):
    print(i)

Output:

1
2
3
4
5
1
2
3
4
5

1. Python range function

The range function is the most used for loops. So, let us discuss more on the range() function.

a. Single argument:

When we give an argument ‘n’ to the range(), then it creates the numbers from 0 to n-1.

Example of Python range() function with one argument:

range(10)

list(range(10))

Output:

range(0, 10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Since we got the output as range(0,10) when we tried to print the range(10), we are converting it into a list to know exactly the values of the sequence.

b. Two arguments:

When we give two arguments (x,y) to the range(), then the sequence of the values from x to y-1 gets created.

Example of Python range() function with two arguments:

list(range(3,9))

Output:

[3, 4, 5, 6, 7, 8]
c. Three arguments:

When we give two arguments (a,b,c) to the range(), then the sequence of the values from x to y-1 gets created. But between each element will have a difference/ a gap of ‘c’.

Example of Python range() function with two arguments:

list(range(1,20,3))

Output:

[1, 4, 7, 10, 13, 16, 19]
d. Negative values:

We can also give the arguments as negative values too. If the first is negative, then we need to give the second value as it would be less than 0. And we know with one argument we get the values from 0 to argument-1.

With two arguments we can give negative values for both, given that the first one is less than the second. This is because the default increment from the preceding value to the current value is 1 to form the sequence.

With three arguments, if we give the third argument negative then we need to make sure the second argument is less than the first. As here decrement by the third value takes place, only if the second value is more than the first one we can get an empty list.

Example of Python range() function with negative values:

list(range(-2,5))

list(range(10,2,-3))

Output:

[-2, -1, 0, 1, 2, 3, 4]
[10, 7, 4]
e. Getting empty sequences:

From the constraints we discussed above we get an empty sequence in the following cases:

A. When the argument given is negative and we gave only one argument

B. When the first argument is more than the second when only two arguments are given or the third argument is positive.

C. When the first argument is less than the second when the third argument is negative.

Example of range() function giving empty sequences:

list(range(4,2))

list(range(-2,-10,2))

list(range(-5,5,-2))

Output:

[]

[]

[]

2. Looping over the iterables

To iterate over the iterables like list, string, set, tuple, and dictionary, for loop is the most common approach used by the programmers. In this instead of using the range() function, we loop over the iterable. While in the case of dictionaries, the iterable loops over the keys. So we can use the iterable to get the corresponding value.

The below examples show the use of for loop over each iterable.

Example of iterating over list:

list1=[1,'r',5.6,[3.2,'y'],7]
for ele  in list1:
    print(ele )

Output:

1
r
5.6
[3.2, ‘y’]
7

Example of iterating over set:

set1={4,2,'y',0.5,'abc'}
for ele  in set1:
    print(ele )

Output:

0.5
2
4
y
abc

Example of iterating over tuple:

tup=('a',4,'gfd',9.2)
for ele in tup:
  print(ele)

Output:

a
4
gfd
9.2

Example of iterating over string:

name='PythonGeeks'
for char in name:
    print(char)

Output:

P
y
t
h
o
n
G
e
e
k
s

Example of iterating over dictionary:

dic={1:'r','y':3.4,6:[3,'t','r'],'e':0}
for key in dic:
    print(key,":",dic[key]) 

Output:

1 : r
y : 3.4
6 : [3, ‘t’, ‘r’]
e : 0

3. Iterating using indices

An alternate method used to loop over the ordered iterables is to find the length using the len() function. And then using it as the argument to the range() function. Then using the iterable as an index to access the elements of the iterable.

The below example shows the way to do so on the list.

list1=[3.7,'u',9,[3,4,5],6.0]
for i in range(len(list1)):
    print(list1[i])

Output:

3.7
u
9
[3, 4, 5]
6.0

4. Python Else statement

Similar to the while loop, we can use the else along with the for loop. This executes ones the for loop ends and the syntax:

for iterator in sequence:
    statement(s)
else:
    statement(s)

Example of Python for loop with else statement:

for i in range(1,6):
    print(i**2)
else:
    print("The for loop ended!")

Output:

1
4
9
16
25
The for loop ended!

We can see that the else block executes even if the for loop runs. If we want the else part to get executed only when the for loop does not execute, then we have to use the break statement. This will end the loop and the else part once the condition is met. If the loop does not execute at least one time, then the break also does not run. So, else part executes.

Example of for loop with else statement and break statement:

for i in range(1,6):
    print(i**2)
    if(i==5): break
else:
    print("This will execute only when the for loop does not run at least one time")

  
for i in range(0):
    print(i**2)
    if(i==5): break
else:
    print("This will execute only when the for loop does not run at least one time")

Output:

1
4
9
16
25
This will execute only when the for loop does not run at least one time

We can see that in the first code, the for loop is executed and when the last case is encountered, the break statement executes and else part is skipped. But in the second case, range(0) gives an empty sequence. So, the for loop does not run at all and the else part executes.

Python Nested Loops

We can also have a loop in another loop and like this, we can have multiple loops nested one in another. The syntax to nest while and for loops is :

for iterator1 in sequence1:
    for iterator1 in sequence1:
        statement(s)
    statement(s)



while condition1:
    while condition2:
        statement(s)
    statement(s)

Examples of nested for and while are given below:

Example of nested while loop in python:

i=1
while(i<=5):
    j=1
    while(j<=i):
        print(j,end=" ")
        j=j+1
    i=i+1
    print()

Output:

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

In this, the outer while loop runs for all i from 1 to 5. And the inner loop runs from 1to the value of ‘i’ in that iteration and prints the values of ‘j’ in the same line. When the inner loop is done, then the value of ‘i’ is incremented to check the condition on the outer loop and a new line is printed using the print().

Example of Python nested for loop:

for i in range(1,6):
    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

In this, the outer for loop runs from 1 to 5 and the inner from 1 to i. And it prints the values of ‘j’. At the end of the inner for loop, the new line is introduced using the print() function.

Python Loop Control Statements

There are three loop control statements in Python that modify the flow of iteration. These are :
1. break
2. continue
3. pass
We will learn about each of these in this section.

1. break statement in python

We can use the break statement to stop the execution of the loop and go out of the loop to execute the remaining part of the program. Look at the below code for more understanding.

Example of Python for loop with a break statement:

list1=[1,2,3,4,5,6,7,8,9,10]
for i in list1:
    print(i)
    if(i==5): break

Output:

1
2
3
4
5

We can see that once the value of i is 5, the condition in if gets satisfied and the break statement executes. And no number after is printed because the control got shifted outside the loop.

Similarly, we can use in while loops. The below example shows this.

Example of Python while loop with a break statement:

while(i<=10):
    print(i)
    if i==5: break
    i=i+1

Output:

1
2
3
4
5

In this example, we can see that when the value is 5, the loop does not run further.

2. Python continue statement:

The continue statement is used to skip that interaction of the loop and go with the next iteration.

Example of for loop with continue statement:

for i in range(1,6):
    if i==3: continue
    print(i)

Output:

1
2
4
5

In the above example, we can see that when the value of i is 3, the execution of the rest of the body after the continue statement is skipped and the next iteration is done. Because of this, the value 3 is not printed, as the print statement is skipped when the value of i is 3.

We can use the continue statement in while loops too.

Example of while loop with continue statement:

i=4
while(i<=9):
    i=i+1
    if(i==9): continue
    print(i)

Output:

5
6
7
8
10

In this example, we can see that when i is equal to 9, the print statement is skipped.

3. Python pass statement:

The pass statement is used to write an empty loop. It is a null statement and is considered as no operation by the compiler. Generally in loops, it assigns the last or end value to the iterator.

Example of Python for loop with pass statement:

for i in 'PythonGeeks':
    pass

print(i)

Output:

s

We can see that the i value got assigned to the last letter of ‘PythonGeeks’ after the loop.

Example of Python while loop with pass statement:

while i<=5:
    i=i+1
    pass

print(i)

Output:

6

Here also we can see that the while loop that the value of i at the end of the loop got assigned with the value 6, which is the end condition.

Python Interview Questions on Loops in Python

Q1. Write a program to find the factorial of a number.

Ans. Factorial of a number ‘n’ is the product of all the numbers from 1 to n. We can take a variable as 1 and use the loop to multiply the variable by the iterator in every iteration.

Example to find the factorial:

i=1
fact=1
while(i<=6):
    fact=fact*i
    i=i+1

print("The factorial of 6 is:",fact)

Output:

The factorial of 6 is: 720

Q2. Given a list of numbers. Print only the even values.

Ans. We can use the continue statement whenever the condition of odd value (num%2==1) is True.

Example of printing only the even values of the list:

list1=[12,4,5,7,23,49,0]
for i in list1:
    if i%2==1 : continue
    print(i)

Output:

12
4
0

Q3. Write a program to print the alternate numbers from 1 to 10 in reverse order.

Ans. We can use the range() function with the arguments as (10,1,-2).

Example of printing alternate numbers in the reverse order:

for i in range(10,1,-2):
    print(i)

Output:

10
8
6
4
2

Q4. Write a function to print the following pattern.
# # # # # #
# # # # #
# # #
#

Ans. We can use the nested loops with the inner loop printing odd number of symbols “#”.

Example of printing a pattern:

for i in range(4,0,-1):
    for j in range(2*i-1):
        print("#",end="")
    print()

Output:

#######
#####
###
#

Q5. Write a program to find the username of a person, which is the key in the dictionary, and print the corresponding code. If the name of the person is not in the dictionary, then telling that the name is not found.

Ans. We can use the else and write the return statement in the loop. Since after the return statement, the other lines of code do not run, the else statement does not execute.

Example of checking username in the dictionary:

def find(name):
    dic={'abc':23, 'xyz':54, 'pqr':90,'poir':432}
    for i in dic:
        if(i==name): return dic[i]
    else:
        print("Sorry, could not find the name")

    
find('pqr')

find('rew')

Output:

90

Sorry, could not find the name

Quiz on Loops in Python

Conclusion

In this article, we learned about loops in Python. We saw for and while loops in detail and then the nested loops. We also discussed the control statements.

Finally, we practiced some coding questions. Hope you understood the concepts covered in this article. Happy learning.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google | Facebook


3 Responses

  1. mike says:

    `help me loop this code with a variable that increases from 0 to 10 and the number of the variable I want is the number of the loop`

    pyautogui.click(301,554)
    time.sleep(3)
    pyautogui.click(301,554)
    pyautogui.write(“210 ” , interval=0.2)
    time.sleep(1)
    pyautogui.click(434,552)
    time.sleep(3)

  2. Md. Murad Hossain says:

    very effective

  3. Pankaj says:

    Explained in better way. Thanks

Leave a Reply

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