Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 7

TOPIC : LOOP/ITERATION STATEMENT IN

PYTHON
LOOP/ITERATION STATEMENTS
• Loop in Python provide the capability to execute a set of
statements repeatedly as long as a particular condition remains
true.
• Python provides two types of loop:
 for loop
 while loop
for loop
The for loop of Python is designed to process the items of any sequence, such as a
list, tuple or a string one by one. It is also called counting loop.
Syntax:
for <variable> in <sequence> :
statements_to_repeat
Examples:
for a in [2,3,4,5]: Output:
print(a) 2
3
4
5

for a in “DPSR”: Output:


print(a) D
P
S
R

for a in (2,3,4,5): Output:


print(a*a) 4
9
16
25
range() function
The range() is a pre defined function in Python and is used to generate a list
containing a sequence of numbers starting with ‘start’ and ending with one less
than the ‘stop’ .
Syntax:
range(start, stop, step)
• Bydefault, the list starts from 0 and in every iteration, it is increamented by one
but we can specify a different increment value by using the step parameter of
range function.
• range(l,u) will produce a list having values starting from l,l+1,l+2,….(u-1). i.e.
lower limit is included in the list while upper limit is not included in the list
Examples:
range(0,5) [0,1,2,3,4]
range(10) [0,1,2,3,4,6,7,8,9]
range(1,10,2) [1,3,5,7,9]
range(5,0) [ ] i.e. empty list as no number falls in
this range from 5 to 0
range(0,-6,-1) [0,-1,-2,-3,-4,-5]
for loop with range() function
The range() function can also be used with for loop to generate a list of numbers.
Syntax:
for <variable> in range(parameters list) :
statements_to_repeat
Examples:
for a in range(5,10): Output:
print(a) 5
6
7
8
9

s=0 Output:
for a in range(1,6,2): Sum=9
s=s+a
print(“Sum=“,s)
for loop Programs

Program 1: To find sum of ‘n’ natural numbers entered by the user.


n=int(input(“Enter any number”))
s=0
for i in range(1,n+1):
s=s+i
print(“Sum of numbers from 1 to n=“,s)

Program 2: To find sum of all elements of a list.


L=[2,5,3,4,6]
s=0
for i in L:
s=s+i
print(“Sum of all elements of list L=“,s)
Thank You

You might also like