For Statement And Range Function With Indexes
Solution 1:
itertools module is a collection of tools for handling iterators
itertools.accumulate - Make an iterator that returns accumulated sums, or accumulated results of other binary functions
from itertools import accumulate
for i in accumulate(range(5)):
print(f'Hello {i}')
Or without any modules
cum_idx = 0for i inrange(5):
cum_idx += i
print(f'Hello {cum_idx}')
Solution 2:
you would need to increment step manually which can be done using a while loop. checkout difference between while and for loop.
The for statement iterates through a collection or iterable object or generator function.
The while statement simply loops until a condition is False.
if you use a while loop your code would look something like this:
count_indexes = 0step = 1while count_indexes < 11:
print("Hello", count_indexes)
count_indexes = count_indexes + stepstep = step + 1
output:
Hello 0
Hello 1
Hello 3
Hello 6
Hello 10
Solution 3:
Range
starts from 0 so you don't need to type it.
Here is sample solution:
counter = 0for i in range(5):
counter += i
print('Hello', counter)
Solution 4:
The numbers are the triangle numbers. There is a closed form for calculating them so you don't need the keep track of an extra variable.
>>>for i inrange(5):...print('Hello', (i+1)*i//2)
Hello 0
Hello 1
Hello 3
Hello 6
Hello 10
Post a Comment for "For Statement And Range Function With Indexes"