4_Aug_for-loop
4_Aug_for-loop
Iterative statements
In Python, iterative statements allow us to execute a block of code repeatedly as long as the condition is True. We also call it a loop statements.
Python provides us the following two loop statement to perform some actions repeatedly
In [ ]:
In [ ]:
Using for loop, we can iterate any sequence or iterable variable. The sequence can be
string, list, dictionary, set, or tuple,range function.
In [ ]: # Syntax of for loop:
In [ ]:
Using the for loop we can repeat the block of statements a fixed number of times. Let’s understand this
with an example.
Fixed number of times: Print the multiplication table of 2. In this case, you know how many iterations you need. Here you need 10 iterations. In such a case use for loop.
2
4
6
8
10
12
14
16
18
20
In [ ]:
range(start, stop,step)
In [2]: print(range(8))
range(0, 8)
In [ ]:
In [3]: a = range(6,9)
print(list(a))
[6, 7, 8]
In [ ]:
In [4]: print(list(range(8)))
[0, 1, 2, 3, 4, 5, 6, 7]
In [ ]:
In [5]: print(list(range(0,8)))
[0, 1, 2, 3, 4, 5, 6, 7]
In [ ]:
In [6]: print(list(range(0,10,2)))
[0, 2, 4, 6, 8]
In [ ]:
In [7]: # in operator
In [8]: a = 22
print(a in [2,34,5,6])
print(a)
False
22
In [ ]:
2
34
5
6
In [ ]:
5
10
15
20
25
30
35
40
45
50
In [ ]:
0
1
2
In [ ]:
17
34
51
68
85
102
119
136
153
170
In [ ]:
In [ ]:
0
17
34
51
68
85
102
119
136
153
17 * 1 = 17
17 * 2 = 34
17 * 3 = 51
17 * 4 = 68
17 * 5 = 85
17 * 6 = 102
17 * 7 = 119
17 * 8 = 136
17 * 9 = 153
17 * 10 = 170
In [ ]:
K o l k a t a
In [ ]:
In [17]: a= [1,2,3,5]
for i in a:
print(i)
1
2
3
5
In [ ]:
1
2
3
5
In [ ]:
1
2
3
5
In [ ]:
name
class
In [ ]:
for i in numbers:
square = i ** 2
print("Square of:", i, "is:", square)
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
*
**
***
****
*****
In [ ]:
In [ ]:
In [25]: # 1
# 22
# 333
# 4444
# 55555
# print like this
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
In [ ]:
In [27]: # 1
# 12
# 123
# 1234
# 12345
# print like this
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
In [ ]:
for x in numbers:
for y in items:
print(x, y)
10 Chair
10 Table
20 Chair
20 Table
In [ ]:
Q.1
Enter a number6
1
3
6
10
15
21
In [ ]:
In [ ]:
In [ ]:
Q.2
enter no.= 6
91
In [ ]:
In [ ]:
Q.3
150
In [ ]:
Q 4.
input = "1234"
23445
18
In [ ]:
Q 5.
first create a empty list ...and append from 1 to 10 number into a empty list.
In [40]: a = []
for i in range(1,11):
a.append(i)
print(a)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [ ]:
In [ ]:
min_val = numbers[0]
In [ ]:
numbers = [10, 20, 30, 40, 50] you have to find out average of this list
In [43]: a=[60,60,60,60,60]
sum=0
count=0
for i in a:
sum+=i
count+=1
print("average is :",sum/count)
average is : 60.0
In [ ]:
add = 0
for i in numbers:
add = add + i
list_size = len(numbers)
average = add / list_size
print(average)
30.0
In [ ]:
In [ ]:
take a input from user (e.g., "12345"), the program will calculate the sum of its individual
digits (1 + 2 + 3 + 4 + 5) and print the result (15).
In [45]: user = input("enter the number = ")
total=0
for i in user:
total+=int(i)
print(total)
In [ ]: