Python for loop

A for loop is used to execute the program for a fixed number of times. The syntax of for loop in Python is different is from the syntax of for loop in C.

Python for loop

A for loop is used to execute the program for a fixed number of times. It can be used to iterate through the elements of a list, tuple etc.

Syntax

In python, a for loop is created using the for keyword. The syntax of for loop in Python is different is from the syntax of for loop in C.

for i in sequence:
    Statement 1
    Statement 2
    Statement n

Example 1

for i in range(1,5):
	print(i)

Example  2 – Reverse for loop

for i in range(4, 0,-1):
    print('The value of i is: '+str(i))

Output

The value of i is: 4
The value of i is: 3
The value of i is: 2
The value of i is: 1

Example 3 – Nested for loop

A loop specifies inside another loop is known as nested loops.

for i in range(1,4):
    for j in range(3,0,-1):
        print("i="+str(i)+" j="+str(j))

Output

i=1 j=3
i=1 j=2
i=1 j=1
i=2 j=3
i=2 j=2
i=2 j=1
i=3 j=3
i=3 j=2
i=3 j=1

Example 4 – For loop over a string

You can print each characters in a string as shown below.

a="Hello"
for i in range(1,5):
	print(i)

Output

H
e
l
l
o

Example 5 – For loop over a list

A list is an ordered collection of items. The following code displays each elements in a list.

a=['a','b','c','d']
for s in a:
    print(s)

Output

a
b
c
d

Example 6 – For loop over a dictionary

In Python, a dictionary is an unordered collection of objects. You can loop over the objects in a dictionary using the following code.

a={'Windows:Microsoft','iPhone:Apple','Android:Google'}
for d in a:
    print(d)

Output

iPhone:Apple
Windows:Microsoft
Android:Google

Example – Break statement in for loop

The break statement can be used to stop the execution of a for loop.

a="Hello_World"
for c in a:
    if c == "_":
        print("Loop terminated")
        break
    print(c)

Example  – continue statement in for loop

The continue statement can be used to skip the current iteration of the for loop.

a=['Python','CSS','JavaScript']for c in a:
    if c == "CSS":
        continue
    print(c) 

Share Tweet Send
Loading...
You've successfully subscribed to Geekinsta
Great! Next, complete checkout for full access to Geekinsta
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.