For loop

Overview of for loop

For loop is use to iterate over a sequence. It can be used with string, tuple, list or dictionary

Below example include list of cities and using for loop to display each city from a list. There is no need of indexing variable

cities = ['Mumbai','Pune','Chennai','Delhi','Bangalore']
for c in cities:
    print(c)

Output

Mumbai
Pune
Chennai
Delhi
Bangalore

Iterating over a string

str = 'Python Programming'
for s in str:
print(s)

Output

P
y
t
h
o
n
 
P
r
o
g
r
a
m
m
i
n
g

Break :- This statement is use to exit from the loop before it iterate through all elements

Below example include list of numbers from 0 to 10. It breaks the loop when the current value of num variable is 4

num = [1,2,3,4,5,6,7,8,9,10]
for n in num:
    print(n)
    if n == 4:
        break

Output

1
2
3
4

Second example

lang = ['Python','Java','C++','Perl','PHP']
for l in lang:
print(l)
if l == 'C++':
break

Output

Python
Java
C++

range()

Use to iterate specified number of times. It starts at 0 by default and increment by 1 and end at the specified value

for x in range(5):
print(x)

Output

0
1
2
3
4

Loop starts at 0 and stop at 4 and not 5

range() can also include second parameter which specify the start position. In the below code, loop starts at 2 and ends at 4 and not 5

for x in range(2,5):
print(x)

Output

2
3
4

Second example : Loop starts at 15 and ends at 19 and not at 20

for x in range(15,20):
    print(x)

Output

15
16
17
18
19

There is also an option of specifying third parameter which defines incremental value. By default, incremental value is 1 but this can be changed to any desired value.

Loop starts at 2 and ends at 10 with incremental value of 3. First value will be 2 then it has to increment by 3 so the next value will be 5 again incrementing the value by 3 and the value is 8. Now if it increment the value by 3, it becomes 11 which is not below 10. Only three values will be printed 2,5 and 8

for n in range(2,10,3):
print(n)

Output

2
5
8

Second Example

for n in range(25,50,5):
print(n)

Output

25
30
35
40
45
Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s