for Loop in Python

A loop is used to execute a statement or group of statements multiple number of times. There are two types of loops in general in python, for loop and while loop.

Let us see for loop in this tutorial.

Read this tutorial for while loop : While Loop in Python

It is used to iterate over a given sequence.

Example: traversing a list or string or an array, etc.

Syntax:

for iterator_var in sequence:
    statement(s)

Python program to print each employee id in an employee list

# Python program to illustrate iterating over a list

employeeIds = [2, 13, 50, 27,66,32]

for eid in employeeIds: print(eid,end=' ') # prints eid value
Output: 2 13 50 27 66 32 

From the above example, eid is a temporary variable, which is used to store the list values one by one

Python program to print even employee ids in an employee list

employeeIds = [2, 13, 50, 27,66,32]
for eid in employeeIds:
    if eid%2 == 0:  # checks whether eid is even or not
        print(eid,end=' ')  # prints eid if it is even

# Output: 2 50 66 32

Example:

Python program to illustrate iterating over a list using for loop

print("List Iteration") 
l = ["python", "programs", "for","us"] 
for i in l: 
	print(i) 
	
# Iterating over a tuple (immutable) 
print("\nTuple Iteration") 
t = ("python", "programs", "for","us") 
for i in t: 
	print(i) 
	
# Iterating over a String 
print("\nString Iteration")	 
s = "Python programs"
for i in s : 
	print(i, end = ' ') 
	
# Iterating over dictionary 
print("\nDictionary Iteration") 
d = dict() 
d['Raju'] = 159
d['Rani'] = 267
for i in d : 
	print("%s %d" %(i, d[i]))
Output:
List Iteration
python
programs
for
us
Tuple Iteration python programs for us String Iteration P y t h o n   p r o g r a m Dictionary Iteration Rani 267 Raju 159

The range() Function

It is used to generate a sequence of numbers, starting from 0 by default, and increment by 1 (by default), and ends at a specified number.

Syntax:

range([start,] stop [, step])
  • start(optional): Starting point of the sequence. If it is not specified, it will start from 0
  • stop(required): Endpoint of the sequence. This item will not be included in the sequence
  • step(optional): Step size of the sequence. If it is not specified, it will be taken as 1 by default

 

Example:

Python Program to print numbers from 0 to 10 using for loop

for i in range(11): # starts at 0, ends at 10 and increments by 1
    print(i,end=' ') # prints i value

 
# Output: 0 1 2 3 4 5 6 7 8 9 10

Example:

Program to print even numbers from 10 to 20 using loop

for i in range(10,21,2):  # starts at 10, ends at 20 increments by 2
    print(i,end=' ')  # prints i value

 
# Output: 10 12 14 16 18 20

Example:

Python Program to print odd numbers from 40 to 20 using for loop

for i in range(39,20,-2):  # starts at 39, ends at 21 and decrements by 2
    print(i,end=' ')   # prints i value

 
# Output: 39 37 35 33 31 29 27 25 23 21

Example:

Python Program to find whether the given number is prime or not using loop

n=int(input("enter a no. \n")) # reads a number from user
nof=0 # assign 0 to nof
for i in range(1,n+1):  # generate numbers from 1 to n
	if n%i==0: # checks if n is divisible by i or not
		nof=nof+1 # incrementing nof by one
if nof ==2:
	print("prime no.") # if nof==2 then prints 'prime no.'
else:
	print("not prime no.") # if nof!=2 then prints 'not prime no.'
Output:
enter a no.
7
prime no.

Example:

Python Program to find factorial of a number using loop

n=int(input("enter a no. \n"))  # reads a number from user
f=1  # assigns 1 to f
for i in range(1,n+1):  # generate numbers from 1 to n
	f=f*i  # multiply and store it
print("factorial of",i,"is",f)   # prints the stored value

Output:

enter a no.
5
factorial of 5 is 120

Example:

Python Program to display a multiplication table using for loop

n = int(input("enter a no. \n"))   # reads a number from user
for i in range(1,11):   # generate numbers from 1 to 10
	print(n,"*",i,"=",n*i)  # print the stored values

Output

Output:
enter a no.
5
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50


Iterating by index of sequences


We can also use the index of elements in the sequence to iterate. The key idea is to first calculate the length of the list and in iterate over the sequence within the range of this length.

# program to illustrate iterating by index 
list = ["python", "programs", "for","us"] 
for index in range(len(list)): 
    print(list[index])
Output:
python 
programs
for
us

Using else statement with for loops:
We can also combine else statement with for loop. But as there is no condition in for loop based on which the execution will terminate so
the else block will be executed immediately after for block finishes execution.

Example:

Python Program to illustrate by combining "else with for"

Let us see an example of for loop with else statement.

list = ["python", "programs", "for","us"] 
for index in range(len(list)): 
    print(list[index])
else: 
    print("Inside Else Block")  
    
Output:
python 
programs
for
us
Inside Else Block