How to use while statement to create a loop in Python

while statement

The while loop statement repeats a block of code based on a condition. If the condition is true it will continue to loop until the condition is false.


x = 1 
while x <= 10: 
   print x 
   x += 1 

The code above generates the following result.

You could also use a loop to ensure that the user enters a name, as follows:


name = '' 
while not name: 
   name = raw_input('Please enter your name: ') 
print 'Hello, %s!' % name 

The code above generates the following result.

else Statement


y = 8#   w w  w. ja v  a2 s. c o m
x = y / 2                                 # For some y > 1
while x > 1:
    if y % x == 0:                        # Remainder
        print y, 'has factor', x
        break                             # Skip else
    x = x-1
else:                                     # Normal exit
    print y, 'is prime'

 

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules