logo codesdope

for Loop in Python


If you are here, it means you are going to be a coder soon. You will solve real-world computer problems, make your own programs, and a lot more. Yeah, sounds good!

Now let's talk about 'for'. It is also a loop like 'while'. Let's see how it works.

  • Python 2
  • Python 3
marks = [78,98,50,37,45]
for m in marks:
	print m
marks = [78,98,50,37,45]
for m in marks:
	print(m)
Output
78
98
50
37
45

Just this and it's done. Let me explain you the code.

for m in marks → 'm' is a variable which will go to every element in the list 'marks' and will take its value.

So, in the first iteration, m will be the 1st element of the list. In the second iteration, m will be the 2nd element of the list an so on.

As you have seen above, in the first iteration the value of m is 78, in the second iteration, its 98, then 50 and so on.

Notice that the body of 'for' loop is also represented by equal indentation (margin) from left.

Example of the sum of marks

  • Python 2
  • Python 3
marks = [78,98,50,37,45]
sum = 0
for m in marks:
	sum = sum+m
print sum
marks = [78,98,50,37,45]
sum = 0
for m in marks:
	sum = sum+m
print(sum)
Output
308

You must have got the code. If not, then let me explain a bit.

sum = 0 → We are taking any variable and assigning it an initial value of 0.
In the 1st iteration
m is 78. So, sum+m is 0+78. Now, the value of sum is 78
In the 2nd iteration
m is 98. So, sum+m is 78+98. Now, the value of the sum is 176.

And similarly at last, sum is 308.

for loop in python
We can also use for loop on tuples and strings. Try it yourself.
Do You Know ?
Table of 12 Add And you get table of 13
12 +1 13
24 +2 26
36 +3 39
48 +4 52
60 +5 65
72 +6 78
84 +7 91
96 +8 104
108 +9 117
120 +10 130

So, let's do it with the help of for loop.

  • Python 2
  • Python 3
table_12 = [12,24,36,48,60,72,84,96,108,120]
table_13 = []
z = 1
for i in table_12:
	table_13.append(i+z) #using append to add an element in front of list
	z = z+1
print table_13
table_12 = [12,24,36,48,60,72,84,96,108,120]
table_13 = []
z = 1
for i in table_12:
	table_13.append(i+z) #using append to add an element in front of list
	z = z+1
print(table_13)
Output
[13, 26, 39, 52, 65, 78, 91, 104, 117, 130]

z = 1 → We have to add 1,2,3... respectively to each element. And that's what we are doing. Add 1 then increase z by 1 for the next turn (z = z+1).

table_13.append() → 'append()' is a function of list which adds an element in front of a list. So, (i+z) will add (12+1),(12+2),...(12+10) in their respective turns in the list.

By writing codes, your mathematics is going to be fun.

How difficult life may seem, there is always something you can do and succeed at.
- Stephen Hawking


Download Our App.
BlogsDope App
Get it on Google Play
Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.