CHINMAYA VIDYALAYA SR SEC SCHOOL CHENNAI 92
CLASS X – LOOPING STATEMENTS IN PYTHON – MASTER NOTES
FOR STATEMENT PROGRAMS
1. frnds=["mini","mitra", "priya", "latha"]
for a in frnds:
print(a)
2. for a in range(1,10): #print only from 1 to 9 not 10
print(a)
3. for a in range(1,11,2): #with step value to print odd numbers
print(a)
4. for a in range(2,11,2 ): #with step value to print even numbers
print(a)
5. for a in range(1,5):
print("*")
6. for a in range(1,5):
print("*"*a)
7. s=0
for a in range(1,11): #print only from 1 to 10 and to find sum
print(a)
s=s+a
print("sum of numbers 1 to 10 = ",s)
8. for a in range(21): #range with 1 value
print(a)
WHILE STATEMENT PROGRAMS
1. #to print numbers from 5 to 15
a=5 #initializing the value of variable a as 5
while a<=15: #loop repeats its block statement till a<=15
print(a) #print the value of a till the loop condition is true
a+=1 #increments the value of a by 1 (a=a+1)
2. #to accept 5 names and print using while loop
cnt=1
while cnt<=5:
nam=input("enter your name")
print("welcome ",nam)
cnt+=1
3. #to print numbers from 1 to 50 but not the numbers 13 and 21
cnt=0
while cnt<=50:
cnt+=1
if cnt==13 or cnt == 21:
continue
print(cnt)
4. # Simple while loop with break
print("While Loop Example:")
counter = 0
while True:
counter += 1
print("Counter:”,counter)
if counter >= 3:
break
print("While loop ended.")
• The while True loop runs indefinitely.
• The counter is incremented on each iteration and printed.
• The loop breaks when counter reaches 3
5. # Simple for loop with break
print("\nFor Loop Example:")
for i in range(5):
print("Index: ",i)
if i == 2:
break
print("For loop ended.")
differentiate FOR and WHILE loop in Python.
Basis of For Loop While Loop
Comparison
Keyword Uses for keyword Uses while keyword
Used For loop is used when the While loop is used when the
number of iterations is already number of iterations is already
known. Unknown.
absence of The loop runs infinite times in Returns the compile time error in
condition the absence of condition the absence of condition
Nature of Once done, it cannot be In the while loop, it can be repeated
Initialization repeated at every iteration.
Functions To iterate, the range or xrange There is no such function in the
function is used. while loop.
Initialization To be done at the beginning of In the while loop, it is possible to
based on iteration the loop. do this anywhere in the loop body.
Syntax for the following:
FOR loop:
for variable in sequence:
# code block
WHILE loop:
while condition:
# code block