While Loop

suggest change

A while loop will cause the loop statements to be executed until the loop condition is falsey. The following code will execute the loop statements a total of 4 times.

i = 0 
while i < 4:
    # loop statements
    i = i + 1

While the above loop can easily be translated into a more elegant for loop, while loops are useful for checking if some condition has been met. The following loop will continue to execute until myObject is ready.

myObject = anObject()
while myObject.isNotReady():
    myObject.tryToGetReady()

while loops can also run without a condition by using numbers (complex or real) or True:

import cmath

complex_num = cmath.sqrt(-1)
while complex_num:      # You can also replace complex_num with any number, True or a value of any type
    print(complex_num)   # Prints 1j forever

If the condition is always true the while loop will run forever (infinite loop) if it is not terminated by a break or return statement or an exception.

while True:
    print "Infinite loop"
# Infinite loop
# Infinite loop
# Infinite loop
# ...

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Loops:
* Loops
* While Loop

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve