Loop in python
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.
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?
Yes, using the loop
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.
for variable in range(start, end, step):
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
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.
n=1 while(n<=10): print(n) n=n+1
Outpur will be: The numbers list from 1 to 10
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()
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 jump statement
break keyword break execution of the program from a current loop
for n in range(1,11): if(n==5): break print(n)
Note: break statement will terminate loop as n value reached at 5
continue keyword jump to next execution of value in a loop, and keep continue.
for n in range(1,11): if(n==5): continue print(n)
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.
for n in range(1,10): if(n==5): pass print("hello")