Boathouse
Boathouse

Reputation: 2825

looping with while statement

I've been trying to learn python recently.

One thing i've seen tutorials do is create loops by making a while statement with a variable that goes up at the end of each statement

example:

loop_end = 0
while loop_end <= 5:
    <do program>
    loop_end = loop_end + 1

This feels odd and a bit ugly. Is there any other way to achieve this effect?

Upvotes: 1

Views: 176

Answers (4)

Marshall Conover
Marshall Conover

Reputation: 845

You want the range function. Here's a loop that prints 0-2:

for x in range(0,3):
    print '%d' % (x)

Check here.

Range is exclusive, so the value on the right will never be met.

You can also denote how the range iterates. For example, specifying an increment of 2 each loop:

for x in range (0, 8, 2)
    print x

will get you

0
2
4
6

as an output.

Upvotes: 1

bcoughlan
bcoughlan

Reputation: 26627

for loop_end in range(6):
    <do program>

Explanation:

Python has the concept of iterators. Different objects can decide how to be iterated through. If you iterate through a string, it will iterate for each character. If you iterate through a list (i.e. array), it will iterate through each item in the list.

The built-in range function generates a list. range(6) generates the list [0,1,2,3,4,5] (so is equivalent to while loop_end <= 5).

(In Python 3, range() returns a generator instead of a list, but you don't need to know that yet ;) ).

Upvotes: 0

mtk358
mtk358

Reputation: 565

http://docs.python.org/library/functions.html#range

for i in range(6):
    # do stuff

Upvotes: 5

jfs
jfs

Reputation: 414215

for loop_end in xrange(6):
    # do program

Upvotes: 3

Related Questions