1

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?

asked Mar 16, 2012 at 20:53
2
  • loop_end += 1 if you still want while loop. Commented Mar 16, 2012 at 22:32
  • Provide links for these tutorials please? Some authors may need to be contacted... Commented Mar 16, 2012 at 22:40

4 Answers 4

5
answered Mar 16, 2012 at 20:56
Sign up to request clarification or add additional context in comments.

Comments

3
for loop_end in xrange(6):
 # do program
answered Mar 16, 2012 at 20:55

Comments

1

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.

answered Mar 16, 2012 at 20:56

Comments

0
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 ;) ).

answered Mar 16, 2012 at 20:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.