Tuesday, 15 January 2013

Python Language Lesson: while loop and break


Python Language Lesson: while loop and break

The for loop is handy if you have a list of items or you know the
maximum number of iterations beforehand. Sometimes, however, you
want to keep looping until some condition becomes true. The while
loop comes in useful in this case. This is how it looks:
i = 10
while i > 5:
print x
i = i - 1
This example prints out 10, 9, 8, 7, 6 on the screen. After the word
while, a conditional expression follows just as in an if statement.
Another typical use is as follows:
while True:
ret = appuifw.query(u"Continue?", "query")
if not ret:
break
Here, the condition is always true, so the loop goes on forever
unless we force the execution out of it using the break statement. The
break statement makes the execution jump out of the loop instantly. In
this example, we show a query dialog in each iteration. The looping
continues until the user cancels the dialog.

No comments:

Post a Comment