1

In Java, we can change the counter variable of a for loop inside its header itself. See below:

for(int i=1; i<1024; i*=2){
    System.out.println(i);
}

I know the following code is wrong. But is there a way to write like that without changing i value inside the loop. I like to make my for loop simple and short :-)

for i in range(1, 1024, i*=2):        
    print(i)
4
  • 2
    @MarounMaroun The step is multiplicative not additive Commented Aug 7, 2017 at 11:16
  • 1
    @MosesKoledoye My bad. Thanks. Commented Aug 7, 2017 at 11:17
  • 2
    In this case, you could use for i in (2**k for k in range(10)) Commented Aug 7, 2017 at 11:18
  • You could try this Python 2.x Integer for i in xrange(0,10,2): print(i) Float: for i in xrange(0.0,10.0,0.2): print(i) Python 3.x Integer: for i in range(0,10,2): print(i) Float: for i in range(0.0,10.0,0.2): print(i) Commented Aug 7, 2017 at 11:24

1 Answer 1

5

You can define your own generator to do that for you:

def powers_of_two(start, end):
    while start < end:
        yield start
        start *= 2

for i in powers_of_two(1, 1024):
    print(i)

which gives:

1
2
4
8
16
32
64
128
256
512
Sign up to request clarification or add additional context in comments.

1 Comment

That makes the code more complex. But hopefully, it does what I expected. :-) Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.