09 For Loops
09 For Loops
09 For Loops
[1]: i = 1
j = i+5
k = j+10
print(i,j,k)
i = 2
j = i+5
k = j+10
print(i,j,k)
i = 3
j = i+5
k = j+10
print(i,j,k)
1 6 16
2 7 17
3 8 18
1 Loops
• There may be a situation when you need to execute a block of code several number of times.
• to iterate over items or elements in a given seq like str, list, tup, set, or dict
• in general. statements are execueted sequentially: The first statement in a function is executed
first. followed by the second and so on.
Iteration or loops - repeat actions
• for loop –> iterates for all the items present in iterating_ sequence:
• while loop –> until the condition satisfies
1
for element in sequence: Body of for
Here, element is the variable that takes that value of the item inside the sequence on each iteration.
Loop continues until all the items completed
[2]: for i in range(1,4):
j = i+5
k = j+10
print(i,j,k)
1 6 16
2 7 17
3 8 18
1 6 16
2 7 17
3 8 18
krishna
print(i,j,k)
3 8 18
print all the numbers between 10 and 50 (both inclusive)
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45 46 47 48 49 50
print even numbers in descending order from 1 to 100
[6]: for i in range(100,1,-1):
print(i,end = ' ')
100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85 84 83 82 81 80 79 78 77 76 75
74 73 72 71 70 69 68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48
47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2
2
write a python program to get all the even numbers for a given range both are inclusive
[9]: lb = int(input('enter lower bound values'))
ub = int(input('enter upper bound values'))
for i in range(lb,ub+1):
if i%2==0:
print(i,end=' ')
35
70
for i in seq:
print(i)
1
2
3
4
5
1
2
3
4
5
srk
3
srk
srk
srk
srk
item1 is at index 0
item2 is at index 1
item3 is at index 2
item4 is at index 3
sum of items in a given list
[16]: l = [1,3,5,7]
sum = 0 # initialization
for i in l:
sum = sum+i
print(sum)
16
sum of even number in between given range (both inclusive
s = 0
for i in range(lb,ub+1):
if i % 2 ==0:
s = s+i
print(i,end = ' ')
print('\nsum is',s)
4
[20]: a = int(input('enter multiplication table: '))
for i in range(1,11):
print(a, '*',i,'=', a*i)
fact = 1
for i in range(a,0,-1):
fact = fact * i
print('factorial of',a,'is',fact)
5
factorial of 5 is 120
i= 0 j= 0
i= 0 j= 1
i= 1 j= 0
i= 1 j= 1
i= 2 j= 0
i= 2 j= 1
ds
5
ds
ds
ds
for i in numbers:
if i == 3:
break
print(i)
1.3.2 Continue
[25]: number = [1,2,3,4,5]
2
4
else:
print('no item left in the list')
6
1
2
3
4
else:
print('no item left in the list')
1
2
3
4