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.
for iterating_var in sequence: statements
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 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
colors = ['Red', 'Blue', 'Green'] for x in colors: print(x)
Red Blue Green
days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') for day in days: print(day)
Monday Tuesday Wednesday Thursday Friday Saturday Sunday
numbers = {100, 200, 300, 400, 500} for i in numbers: print(i)
100 200 300 400 500
word = 'python' for letter in word: print(letter)
p y t h o n
thisdict = { 'year': '2000', 'month': 'March', 'date': 15 } for day in thisdict: print(day) for day, value in thisdict.items(): print(day,value)
#Output of first for loop date month year #Output of second for loop date 15 month March year 2000