Professional Documents
Culture Documents
for c in “python”:
print(c)
output:
p
y
t
h
o
n
Example
for s in (1,2,3):
print(s+10)
output:
11
12
13
for loop with range function
num=int(input("enter a number")) #3
factorial=1
if num<0:
print("negative!Invalid")
elif num==0:
print(“factorial of “num
is ”, 1)
else:
for i in range(1,num+1):#[1,2,3]
factorial=factorial*i
print("factorial of ",num,"is",factorial)
while loop
1. Initialization Expression
2. Test Expression
3. Body of the loop
4. Update Expression
EXAMPLE
nterms = int(input("How many terms? "))
n1, n2 = 0, 1
count = 0
while count < nterms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
output:
How many terms? 6
0
1
1
2
3
5
Endless loop
The loop variable should be updated inside the body of the while in a
way that after some time the test condition becomes false otherwise
the loop will become an endless loop or infinite loop.
Example:
a=5
while a>0:
print(a)
print(“&&&&&”)
What is the output when the input is i)5
ii)0 ?
n=int(input("Enter N"))
i=1
sum=0
while i<n:
if i%2==0:
sum=sum+i
i=i+1
print(sum)
output
b) x=10
y=0
while x>y:
print(x,y)
x=x-1
y=y+1
c) keepgoing=True
x=100
while keepgoing:
print(x)
x=x-10
if x<50:
keepgoing=False
d) x=45
while x<50:
print(x)
e) for x in [1,2,3,4,5]:
print(x)
f)for x in range(5):
print(x)
g)for p in range(1,10):
print(p)
h)for q in range(100,50,-10):
print(q)
i)for z in range(-500,500,100):
print(z)
j)for y in range(500,100,100):
print("*",y)
k) x=10
y=5
for i in range(x-y*2):
print("%",i)