What is the loop in python?
Repetition of any statement or code is called a loop.
What is the use of a loop?
Let’s imagine we want to display the city name “Delhi” 10 times, so what will be our program.
we will simply write a print function containing string “Delhi” 10 times.
Example
Save: loop_example.py
print("Delhi")
print("Delhi")
print("Delhi")
print("Delhi")
print("Delhi")
print("Delhi")
print("Delhi")
print("Delhi")
print("Delhi")
print("Delhi")
As we can see there is a lot of statements to print Delhi, now the question arises in our mind.
Question: can we minimize this?
Answer:
Yes, using the loop
Save: loop.py
for n in range(1,11,1):
print("Delhi")
Note: the output of this program will be the same as out of the above program.
In python, there are two types of loop.
- for loop
- while loop
for loop in python
The for loop uses range() function has three parameters named to start, end, and steps, the third parameter step has default value 1 can be optional, and the first parameter is included and the second parameter is excluded.
Syntax:
for variable in range(start, end, step):
statements
Example
for n in range(1, 11, 1):
print(n)
In this program 1 is included and 11 is excluded and number will be increment by 1
Output
1
2
3
4
5
6
7
8
9
10
While loop in python
Most of the people who are computer science students had been read C, C++ programming before learning the python programming, so as you learned about while loop in C, C++ programming, same as while loop is in python programming.
Syntax
start
while(condition):
statements
step
Example
n=1
while(n<=10):
print(n)
n=n+1
Outpur will be: The numbers list from 1 to 10
Nested Loop
A loop used within another loop is called the Nested loop.
for nested loop
A for loop within other for loop is called for nested loop.
for x in range(1, 5):
for y in range(1,5):
print("*",end=" ")
print()
Output:
*****
*****
*****
*****
*****
while nested loop
A while loop within a while loop is called while nested loop.
x=1
while(x<=5):
y=1
while(y<=5):
print("*",end=" ")
y=y+1
print()
x=x+1
Jump statements in python
- break
- continue
- pass
break jump statement
break keyword break execution of the program from a current loop
Example
for n in range(1,11):
if(n==5):
break
print(n)
Output:
1
2
3
4
Note: break statement will terminate loop as n value reached at 5
continue statement
continue keyword jump to next execution of value in a loop, and keep continue.
Example
for n in range(1,11):
if(n==5):
continue
print(n)
Output:
1
2
3
4
6
7
8
9
10
Note: program execution will be next as n value reached at 5.
pass jump statement
Just pass control to the next statement, as loop and function can’t have an empty body, so we can write pass statements to run code perfectly.
Example
for n in range(1,10):
if(n==5):
pass
print("hello")
output:
hello