goodgrief
goodgrief

Reputation: 408

Python Range Step Increasing

Is it possible to increase each step in range? Something like this:

    for num in range(1, 40, i++) :
       print(i)
...
1
2
3
4
...

Or step in range has only fixed size?

Upvotes: 1

Views: 6452

Answers (4)

Ashwin Singaram
Ashwin Singaram

Reputation: 11

Using For loop

j = 0
for i in range(1,22):
    j += i
    if j <= 22:
        print(j, end=" ")

Output: 1 3 6 10 15 21

Upvotes: 1

Don
Don

Reputation: 17606

A while loop will result in cleaner code:

step = 1
i = 1
while i < 40:
    print i, step
    i += step
    step +=1

result:

1 1
2 2
4 3
7 4
11 5
16 6
22 7
29 8
37 9

Upvotes: 1

SiHa
SiHa

Reputation: 8410

I think you want an increasing step size with each iteration?

The code below does this

>>> for i in (i+sum(range(i)) for i in (range (1,10))):
...  print i
...
1
3
6
10
15
21
28
36
45
>>>

Upvotes: 2

user2314737
user2314737

Reputation: 29327

Yes, step in range has fixed size.

Something like this gives the output you want.

>>> j=0
>>> for i in xrange(1,40):
    j+=i
    print j

Upvotes: 2

Related Questions