For Loop in Python

Updated: May 18


A loop is a used for iterating over a set of statements again and again. There are three types of loops for, while and do-while in python.

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:

Program to print squares of all numbers present in a list

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

sq = 0

for i in num:

sq = i*i

print(sq)

Output:

1

4

9

16

25

Python for loop example using range () function

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

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



Recent Posts

See All

Python Modules

A module is a file containing Python definitions and statements. A module can characterize functions, classes and variables. A module can likewise incorporate runnable code. Gathering related code int

Command Line Arguments in Python

Command Line Arguments are the arguments that are specified after the name of the program in the command line shell of the operating system. Python gives different ways of dealing with these types of