DEV Community

Cover image for Python for loop
Python64
Python64

Posted on

Python for loop

In the Python programming language, the for loop is often used to repeat code. Another word for "repeat code" is iteration.

Other than iterating over code, a for loop can iterate any sequence of items, such as a list or a string.

grammar:

for loop syntax is as follows:

   for iterating_var in sequence:
       statements (s)

flow chart:

The control flow graph shows the execution of a for loop

python for loop

Example:

#!/usr/bin/python
#-*- coding: UTF-8 -*-

for letter in 'Python': # first instance
   print('current letter:', letter)

fruits = [ 'banana', 'apple', 'mango']
for fruit in fruits: # second instance
   print('current letter:', fruit)

print("Good bye!")

Examples of the above output:

current letter: P
current letter: y
current letter: t
current letter: h
current letter: o
current letter: n
current letter: banana
current letter: apple
current letter: mango

by an iterative sequence index

You can traverse through the execution cycle by index, the following examples:

#!/usr/bin/python
#-*- coding: UTF-8 -*-

fruits = [ 'banana', 'apple', 'mango']
for index in range(len(fruits)):
    print("Current fruit:", fruits[index])

print("Good bye!")

Examples of the above output:

Current fruit: banana
Current fruit: apple
Current fruit: mango
Good bye!

The above examples we use the built len() function and range(), len() function returns the length of the list, i.e. the number of elements. range returns a sequence number.

Other examples

Print a triangular array 1-9:

#!/usr/bin/python
# - * - coding: UTF-8 - * -

for i in range (1,11):
    for k in range (1, i):
        print(k, end=''),
    print("\n", end='')

Example of the above output:


1
12
123
1234
12345
123456
1234567
12345678
123456789

You can also use a for loop on a dictionary, but this works a bit differently:

d = {'x': 1, 'y': 2, 'z': 3} 
for k,v in d.items():
    print(k, 'corresponds to', v)

Top comments (0)