Scripting >> Python >> Examples >> Loops >> How to use while loop

Example 1

whileloop1.py - Finite loop

count = 0
while (count < 9):
print 'The count is:', count
count = count + 1

print "Good bye!"


Example 2

whileloop2.py - Infinite loop

var = 1
while var == 1 : # This constructs an infinite loop
num = raw_input("Enter a number :")
print "You entered: ", num

print "Good bye!"

 

Example 3

whileloopbreak.py

 

while True:
   x = int(raw_input("Enter an integer: "))
   if x == 0 :
      print("Zero, exiting")
      break
   elif x < 0:
      print("Negative integer")
   else:
      print("Positive integer")
 

 

Example 4

read input, integer N between 1 and 20

for all non-negative integer less than N, print the square of the integer

N=int( raw_input() )
if N>=1 and N<=20 :
   i=0
   while i<N :
      v=i*i
      i=i+1
      print v