Python - For Loop

Python - For Loop


Previous Page

The for loop

The for loop in Python is used to iterate over a given sequence and executes a set of statements for each element in the sequence. A sequence can be any data structure like list, tuple, set, string and dictionary etc. Along with this, a range()function can also be used as an iterable.

Syntax


for iterating_var in sequence:
      statements

Flow Diagram:

Python For Loop

For loop using range():


for i in range(4):
    print(i, i * 2)
for j in range(2, 6):
    print(j, j ** 2)
for k in range(10, 2, -2):
    print(k)

Output

#Output of first for loop
0 0
1 2
2 4
3 6
#Output of second for loop
2 4
3 9
4 16
5 25
#Output of third for loop
10
8
6
4

For loop over List

colors = ['Red', 'Blue', 'Green']
for x in colors:
    print(x)

Output

Red
Blue
Green

For loop over Tuple

days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
for day in days:
    print(day)

Output

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

For loop over Set

numbers = {100, 200, 300, 400, 500}
for i in numbers:
  print(i)

Output

100
200
300
400
500

For loop over String

word = 'python'
for letter in word:
  print(letter)

Output

p
y
t
h
o
n

For loop over Dictionary

thisdict = {
  'year': '2000',
  'month': 'March',
  'date': 15
}
for day in thisdict:
  print(day)
for day, value in thisdict.items():
    print(day,value)

Output

#Output of first for loop
date
month
year

#Output of second for loop
date 15
month March
year 2000



Recommended Pages

  • Next Page


Previous Page