Skip to content Skip to sidebar Skip to footer

For Statement And Range Function With Indexes

For my assignment, I have to use a for loop and a range function for a program to print out the following, each on a separate line so it looks like a list. Hello 0 Hello 1 Hello 3

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"