Thread: Loops in Python
View Single Post
Old Jan 5th, 2007, 2:56 PM   #3
Dietrich
Professional Programmer
 
Dietrich's Avatar
 
Join Date: Feb 2005
Posts: 434
Rep Power: 4 Dietrich is on a distinguished road
There are several ways to stop a while loop:
# the while loop needs a True condition, here x < 10 to run
# and will stop running on False, when x goes to 10 or above
x = 0
while x < 10:
    # do something with x
    print x
    # increment x by 1, same as x = x + 1
    x += 1

print

# 'while True' would be an endless loop, so you need to break it
# with a break condition (an if statement), stops when x is 10 or higher
x = 0
while True:
    # do something with x
    print x
    x += 1
    if x >= 10:
        break

"""
output in either case -->
0
1
2
3
4
5
6
7
8
9
"""
With the while loop you can do cute things like this:
# whittle down a string with while:
s = "internets"
# string s is True until it's empty
while s: 
    print s
    # each time around remove one char from the end
    s = s[:-1]

"""
output -->
internets
internet
interne
intern
inter
inte
int
in
i
"""
__________________
I looked it up on the Intergnats!

Last edited by Dietrich; Jan 5th, 2007 at 3:24 PM. Reason: more
Dietrich is offline   Reply With Quote