![]() |
Loops in Python
This question came from a hijacked thread. I thought it important enough to put it in its own thread with the proper title.
What loops does Python offer and what are they used for? I might add, that our friend Arevos gave one good answer here: http://www.programmingforums.org/for...122207-30.html |
I don't think you can get a much better answer than his reply. Certainly his first sentence is virtually THE definitive answer to the second question. I agree with your reason for restating it here, however.
|
There are several ways to stop a while loop:
:
# the while loop needs a True condition, here x < 10 to run:
# whittle down a string with while: |
Another way of breaking a while loop - or even nested while loops -- is to use a flag. If you find yourself using this technique, though, you probably need to redesign:
:
flag1 = FalseA sometimes useful trick for getting out of nested loops is to raise an exception - StopIteration is the clearest, (use sparingly - a redesign/restructure is normally better): :
def myfunc(i, j): |
Here is an example of using a recursive function as a while loop with a name:
:
def count_to_9(x):If you ever have to break out of some badly nested loops, put them into a function and use return to break out. |
| All times are GMT -5. The time now is 10:12 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC