The same code can be executed multiple times.
Also, we can iterate lists, strings, etc using the loop.
Space(“ ”) is also considered at the time of iterating in python.
Ex: “ ABCD”. Length is 5.
Python has 2 types of loops:
while
for
1. While
In python, while loop is used to execute the same code repeatedly until a given condition is satisfied. Once the condition becomes false, the next line immediately after the loop in program is executed.
Syntax:
while <condition>:
stmt1
.
.
Stmtn
example :
pickupnum = 5
guess = 0
while guess != pickupnum:
guess = int(input("Guess the number: "))
if guess != correctNumber:
print('False guess')
print('You guessed the correct number')
#while with else
Syntax:
while condition:
#execute these statements
else:
#execute these statements
2. For
when you have a block of code which you want to repeat a fixed number of times. In Python, there is no C style for loop. i.t condition type for loop
syntax:
for itr_var in sequence:
stmt1
for i in range(0,5):
print(i)
Iterate list
list = ["Mahesh","Ganesh","Rajesh","Jayesh"]
for name in list:
print(name)
Iterate string
str = "Mahesh"
for char in str:
print(char)
what if you need index?
range function
for i in range(len(list)):
print(list[i])
enumerate function
for i,name in enumerate(list):
print(name)
Example Addition of list
list = [11,34,22,33,44,55,66,88]
sum = 0
for num in list:
sum += num
print(sum) #check pythontutor.com
Nested loop
for i in range(1,5):
for j in range(1,6):
print(j,i,end = ' ')
print('\n')
print("---------------------------------"
for i in range(1,6):
for j in range(1,6):
print(i,j,end = ' ')
print('\n')