Repeat

For Loop

Python

 

For loop

Python 2.7
for count in range(5, 0, -1):
    print(count)

The for keyword is used to iterate over sequences.

It has a different syntax compared to other Programming Languages and works more like a ForEach.

Here, range() is creating a sequence of numbers, starting from 5 inclusive, decrementing to 0 exclusive, with each number is -1 difference to the previous one.

Here are more examples of range() method:

r1 = range(5)      # [0,1,2,4]
r2 = range(1,5)    # [1,2,3,4]
r3 = range(1,5,2)  # [1,3]
r4 = range(5,0,-1) # [5,4,3,2,1]

This will print 5 4 3 2 1 on Console.

 

Single For loop Statement

Python 2.7
for count in range(5, 0, -1): print(count)

If you only have one statement in your blocks or multiple statements separated by a semicolon (;) in one line, you can have them on the same line as the block header.

 

ForEach loop

Python 2.7
animals = ["Cat", "Dog", "Cow"];

for animal in animals:
    print(animal)

As mentioned before, for works on any iterable objects similar to ForEach in other Programming Languages.

for x in [1,2,3]: print(x)      # 1 2 3
for x in (1,2,3): print(x)      # 1 2 3
for x in {1,2,3}: print(x)      # 1 2 3
for x in {1:'a',2:'b',3:'c'}: print(x)  # 1 2 3
for x in "123":   print(x)      # 1 2 3

This will print Cat Dog Cow on Console.

 

ForEach loop on Dictionary

Python 2.7
dict1 = {'name': 'Sam', 'age': 25}

for key, value in dict1.items():
    print(key + ':' + str(value))

You can iterate over keys in a Dictionary using for.

Dictionaries in Python 2.7 and later have items() method on them which helps to have better syntax for iterating over them.

This will print name:Sam age:25 on Console.

 

ForEach loop on String

Python 2.7
str1 = "Hello World!"

for ch in str1:
    print(ch + ',')

You can iterate over characters in a String using for.

This will print H,e,l,l,o, ,W,o,r,l,d,!, on Console.