1

so evidently you write for loops in python int he following:

for i in range(1, 5):
    print i

but what if I'm actually using i as a counting trick and I specifically wanna do something like:

for (int i = 100; i > 20; i--)

or

for (int i = 0; i < 20 ; i += 2)

do you seriously have to write this in the body of the loop rather than the signature....

2
  • If you're using Python 2, use xrange instead of range in for loops (and anywhere else you don't actually need the whole range as a list). Commented Mar 16, 2011 at 3:58
  • While both of your examples can be trivially done with range(), in practice you will find that you should very rarely use it when you write for loops in Python. Commented Mar 16, 2011 at 8:53

3 Answers 3

5

Different languages use different semantics to say the same thing. You can use the range function in several ways and it has as its arguments:

range(start, stop, jump)

So I can do

range(10, 1, -2)

to get a list like:

[10, 8, 6, 4, 2]

Using the three arguments of range you can get back to your counting tricks from C#, C++, C or Java.

Sign up to request clarification or add additional context in comments.

Comments

3

This should work:

for i in range(100,20,-1): 
    print i

and

for i in range(0, 20, 2): 
    print i

Comments

1

You do something like this:

for i in range(100,20,-1):
   print i

or

for i in range(0,20,2):
   print i

Comments

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.