top of page
Search

# For Loop in Python with Example

Updated: Feb 17, 2022

for () loop is a counting loop and repeats its body for a pre-defined number of times. It is a very versatile statement and has many forms.

Syntax:

for <variable> in <sequence>:

Here <variable> is a variable that is used for iterating over a <sequence>. All iteration it takes the next value from <sequence> until the last of series is reached.

Example:

1. Write a program to print first 20 even numbers.

Program:

for i in range (1,11):

b=2*i

print(b)

i=i+1

Output:

2

4

6

8

10

12

14

16

18

20

2. Write python Program to print squares of all numbers present in a list.

Program:

num = [1, 2, 3, 4, 5]

sq = 0

for i in range num:

sq = i*i

print(sq)

Output:

1

4

9

16

25

3. Write Python for loop example using range () function

Program:

Program to print the sum of first 3 natural numbers

sum = 0

for i in range(1, 4):

sum = sum + i

print(sum)

Output:

6

4. Write a program print all even numbers between 50 and 100 included both.

Program:

for i in range (50,101):

if i%2==0:

print("The even number is",i)

i=i+1

Output:

The even number is 50

:

:

:

:

The even number is 100

5.Write a program to calculate and print the following series 1,4,9,16,25,....20 terms.

Program:

for i in range (1,21):

print(i*i)

Output:

1

4

9

16

25

:

:

400

6. Write a program to print will numbers between 30-70 which are divisible by 3.

Program:

for i in range (30,70,3):

if i%3==0:

print(i)

i=i+3

Output:

30

33

36

:

:

69

7. Write a program to print all the prime numbers between 1 to 100.

Program:

for i in range (2,100):

for j in range (2,i):

if i%j==0:

break

else:

print(i)

Output:

2

3

5

7

11

:

:

97

For loop with else block

for i in range(5):

print(i)

else:

print("The loop has completed execution")

Output:

0

1

2

3

4

The loop has completed execution

Nested For loop in Python

When a for loop is present inside another for loop then it is called a nested for loop.

for i in range(3):

for j in range(9, 13):

print(i, ",", j)

Output:

0 , 9

0 , 10

0 , 11

0 , 12

1 , 9

1 , 10

1 , 11

1 , 12

2 , 9

2 , 10

2 , 11

2 , 12

For Loop Program Video in Python: