Python For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
This is less like the for keyword in other programming languages, and works
more like an iterator method as found in other object-orientated programming
languages.
With the for loop we can execute a set of statements, once for each item in a
list, tuple, set etc.
Example 1: Print the first 10 natural numbers using for loop.
# between 0 to 10
# there are 11 numbers
# therefore, we set the value
# of n to 11
n = 11
# since for loop starts with
# the zero indexes we need to skip it and
# start the loop from the first index
for i in range(1,n):
print(i)
Copy code
Output
1
2
3
4
5
6
7
8
9
10
Example 2: Python program to print all the even numbers within the given range.
# if the given range is 10
given_range = 10
for i in range(given_range):
# if number is divisble by 2
# then it's even
if i%2==0:
# if above condition is true
# print the number
print(i)
Copy code
Output
0
2
4
6
8
Also Read: Understanding Python for loop with example
Example 3: Python program to calculate the sum of all numbers from 1 to a given
number.
# if the given number is 10
given_number = 10
# set up a variable to store the sum
# with initial value of 0
sum = 0
# since we want to include the number 10 in the sum
# increment given number by 1 in the for loop
for i in range(1,given_number+1):
sum+=i #sum=sum+i
# print the total sum at the end
print(sum)
Copy code
Output
55
Example 4: Python program to calculate the sum of all the odd numbers within the given
range.
# if the given range is 10
given_range = 10
# set up a variable to store the sum
# with initial value of 0
sum = 0
for i in range(given_range):
# if i is odd, add it
# to the sum variable
if i%2!=0:::
sum+=ii
# print the total sum at the end
print(sum))
Copy code
Output
25
Example 5: Python program to print a multiplication table of a given number
# if the given range is 10
given_number = 5
for i in range(11):
print (given_number," x",i," =",5*i)
Copy code
Output
5x0=0
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Example 6: Python program to display numbers from a list using a for loop.
# if the below list is given
list = [1,2,4,6,88,125]
for i in list:
print(i)
Copy code
Output
1
2
4
6
88
125