Loading, please wait...

A to Z Full Forms and Acronyms

What is Python Loop | Python Tutorial

This article is all about the loops in python, the statements that we can use with these loops like break, continue , else.

Python Loops


Through this article, we are going to discuss loops in python, topics that we will cover in this article are
• What is the loop?
• Types of the loop in Python
• The While loop
• Use of break statement in ‘while’ loop
• Use of continue statement in ‘while’ loop
• Use of else statement in ‘while’ loop
• The For loop
• Loop through the string
• Break statement with ‘for’ loop
• Continue statement with ‘for’ loop
• Else statement with ‘for’ loop
• Use of Range function
• Nested Loop

1. What is a loop?
A loop may be a programming structure that repeats a sequence of instructions until a selected condition is met. We use loops to cycle through values, add sums of numbers, repeat functions, and many other things.

2. Types of the loop in Python?

There are two primitive loop commands in Python which are mentioned below:
1. while loops
2. for loops

3. The While loop
We can execute a group of statements as long as a condition is true
With a while loop so, let’s look at an example for better understanding.
Syntax:

while expression:
    condition

Example code:

#Print i as long as k is less than 5:
k = 0
while k < 6:
  print(k)
  k += 1

#output
0
1
2
3
4
5

Note:
1. Incrementing k is important otherwise the loop will continue forever.
2. The while loop requires relevant variables to be ready, in this example, we need to define an indexing variable ‘k’ which we set to 0.

4. Use of break statement in ‘while’ loop
This statement can be used with ‘while’ loop to stop the loop even if the while condition is true, let’s look at the code example for better understanding.

#Exit the loop when i is 4:

i = 1
while i < 6:
 print(i)
 if i == 4:
  break
 i += 1
#output:
1
2
3
4


5. Use of continue statement in ‘while’ loop
This statement can be used with ‘while’ to stop the current iteration, and continue with the next:

#Continue to the next iteration if i is 7:

i = 0
while i < 10:
 i += 1
 if i == 7:
   continue
 print(i)
#output:
1
2
3
4
5
6
8
9
10

 

6. Use of else statement in ‘while’ loop
This statement can be used with ‘while’ loop to run a block of code once when the condition no longer is true:

Print a message once the condition is false:

k = 0
while k < 6:
 print(i)
 k += 1
else:
print("k is no longer less than 6")
#output:
0
1
2
3
4
5
k is no longer less than 6

7. The For loop

Points to be noted:

• A for loop is used for iterating over a sequence (that can be either a list, a tuple, a dictionary, a set, or a string).
• unlike the for a keyword in other programming languages, it works more like an iterator method as found in other object-oriented programming languages.
• With the for loop we can execute a set of statements, once for each item in a list, tuple, set, etc.

let’s see how it works over a sequence.

#Print each fruit in a fruit list:

languages = ["english", "hindi", "math", 'science', 'social science']
for x in languages:
 print(x)
#output:
english
hindi
math
science
social science


NOTE: The for loop does not require an indexing variable to set beforehand.

8. Loop through string

Strings are iterable objects, they contain a sequence of characters, let’s see how we can loop through Strings:
Loop through the letters in the word "computer":

for i in "computer":
 print(i)
#output
c
o
m
p
u
t
e
r

 

9. Break statement with ‘for’ loop
The break statement can be used with ‘for’ loop to stop the loop before it has looped through all the items:

For Example

#Exit the loop when j is "java":

languages = ["python", "C",'C++', 'java', "lisp"]
for j in languages:
 print(j)
 if j == "java":
  break
  #output:
  python
C
C++
java


For Example
Exit the loop when x is "java", but this point the break comes before the print:

languages = ["python", "C", 'C++' , 'java', 'lisp']
for x in languages:
 if x == "java":
  break
 print(x)
#output:
python
C
C++


10. Continue statement with ‘for’ loop
With the continue statement we will stop the present iteration of the loop, and continue with the next:

Example

languages = ["python", "C", 'C++' , 'java', 'lisp']
for x in languages:
 if x == "java":
  continue
 print(x)
#output:
python
C
C++
lisp

11. Use of Range function

1. To loop through a set of code a specified number of times, we can use the range() function,

2. The range() function returns a sequence of numbers, ranging from 0 by default, and increments by 1 (by default), and ends at a specified number.

Example
Using the range() function:

for x in range(10):
 print(x)
#output:
0
1
2
3
4
5
6
7
8
9

Note that range(10) include 0 and exclude 10

The range() function defaults to 0 as a starting value, however, if we want to specify the starting
value, we can do it by adding a parameter: range(2, 10), which means values from 2 to 10 (but not including 10):

 Using the start parameter with range():

for x in range(2, 6):
  print(x)
#output:
2
3
4
5

• The range() function defaults to increment the sequence by 1, however, it is possible to specify
the increment value by adding a 3rd parameter: range(2, 30, 3):

 Increment the sequence with 3 (default is 1):

for x in range(2, 30, 3):
 print(x)
#output:
2
5
8
11
14
17
20
23
26
29

12. else statement with ‘for’ loop

The else keyword during a for loop specifies a block of code to be executed when the loop is finished:

Example
Print all numbers from 0 to five, and print a message when the loop has ended:

for x in range(6):
 print(x)
else:
 print("loop ended!")
#output:
0
1
2
3
4
5
loop ended!

13. Nested Loop
A loop inside a loop is called Nested Loop.
The "inner loop" is going to be executed just one occasion for every iteration of the "outer loop". let’s look at the example code for better understanding.

Example
Print roll no for every student:

roll_no = [20, 21, 22, 23, 24]
student = ["Rohan", "Sohan"]

for x in roll_no:
 for y in student:
  print(x, y)
#output:
20 Rohan
20 Sohan
21 Rohan
21 Sohan
22 Rohan
22 Sohan
23 Rohan
23 Sohan
24 Rohan
24 Sohan

14. Use of pass Statement

If for some reason you have a loop with no content, then pass statement can help to avoid getting an error because for loop cannot be empty.

For Example
 

for x in [0, 1, 2]:
    pass
A to Z Full Forms and Acronyms

Related Article