Loops
Loops
While
n=5
Repeated Steps
No Yes Program:
n>0? Output:
print n n=5 5
while n > 0 : 4
print (n) 3
n = n -1
n=n–1 2
print ('Blastoff!‘) 1
print (n) Blastoff!
print 'Blastoff' 0
Loops (repeated steps) have iteration variables that
change each time through a loop. Often these iteration
variables go through a sequence of numbers.
n=5
An Infinite Loop
No Yes
n>0?
...
print 'Done'
Finishing an Iteration with continue
• The continue statement ends the current iteration and jumps to the top
of the loop and starts the next iteration
while True:
> hello there
line = input('> ')
hello there
if line[0] == '#' :
> # don't print this
continue
> print this!
if line == 'done'
print this!
: break
> done
print (line)
Done!
print ('Done!‘)
No
True ? Yes
while True:
line = input('> ’) ....
if line[0] == '#' :
continue
if line == 'done' : continue
break
print (line)
...
print ('Done!‘)
print 'Done'
Example: sum of n number of
elements
sum=0
n=int(input('enter no of elements'))
while n>0:
x=int(input('enter element'))
sum=sum+x
n=n-1
print('sum',sum)
Example: factorial of a number
n=int(input('Enter a no'))
i=1
fact=1
if n==0:
print('factorial of 0 is 1')
while i<=n:
fact=fact*i;
i=i+1
print(fact)
Example: break and continue
while True:
ch=input('enter a character')
if ch=='a' or ch=='e‘ or ch==‘i’ or ch==‘o’ or ch==‘u’ :
print('vowel')
continue
else:
print('consonant')
break
Exercise:
1. Write a program to calculate the average of N numbers.
2. Write a program to print alphabets from a-z
3. Write a program to print all natural numbers in reverse from n to 1.
4. Write a program to print all even numbers between 1 to 100
5. Write a program to calculate the sum of all even numbers between 1
to 100.
6. Write a program to print multiplication table of any number.
Output Based
Output Based
i = 15 i = 15
while i>=0: while i>=0:
print(i) print(i)
i=i-1 i=i+1
Contd.
while n != 0: i=1
print(n) while True:
n -= 1 if i%3 == 0:
else: break
print("what the...") print(i)
i+=1
Contd.
i=1 i=5
while True: while True:
if i%0O7 == 0: if i%0O9 == 0:
break break
print(i) print(i)
i=i+1 i+=1
Contd.
i=1 i=1
while True: while False:
if i%2 == 0: if i%2 == 0:
break break
print(i) print(i)
i+=2 i+=2
Contd.
True = False i=0
while True: while i < 5:
print(True) print(i)
break i+=1
if i == 3:
break
else:
print(0)