0

Can I replace while loop with range function. I am using following code

check = 0
while check<5:
      print check
      check+=2

I am writing in following way

for _check in range(0,5,2):
     print _check

is it correct way?

> Editing My question

if I am not using _check variable inside for loop. Can I avoid to declare also

1
  • maybe just a typo, but there seems to be a mistake in the first sample proposed: the last line should ne check+=2 Commented Feb 25, 2014 at 11:28

2 Answers 2

7

Yes, you are using range() correctly, but you may want to use xrange() instead here:

for check in xrange(0, 5, 2):
    print check

xrange() produces the same results when iterated over, but doesn't build a whole list of all possible indices first, and as a result uses less memory:

>>> range(0, 5, 2)
[0, 2, 4]
>>> xrange(0, 5, 2)
xrange(0, 6, 2)

Since the end-point is not included in the values, it doesn't matter if you use 5 or 6 here as the endpoint, it is just calculated for you from the input parameters.

If you are not using the loop variable, you can use _ to indicate that you are ignoring it in the loop. This is just a naming convention:

for _ in xrange(0, 5, 2):
    # do something 3 times.

in which case you may as well just calculate how many indices there are between 0 and 5 with a step of two and simplify your loop to:

upper_limit, step = 5, 2
for _ in xrange((upper_limit - 1 + step) // step):
    # do something 3 times.
Sign up to request clarification or add additional context in comments.

Comments

3

Regarding the original while loop, using check = check + 1

for x in xrange(5):
    print x

See the documentation here for more information on control flow tools (like loops).

EDIT

If you want to increment by 2 during each iteration, you can use the above code with the increment specified:

for x in xrange(0,5,2):
    print x

2 Comments

The edit corrected the syntax, it was clear (to me at least) that the OP wanted the while loop to increment in steps of two. Or was there a grace-period edit that changed the check + 1 into a check + 2?
Yes martijn - the original question had check += 1 in the while loop.

Your Answer

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.