Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
Hello 6
Hello 10

I know that you have to create two variables, one that keeps track of the number of indexes and another that prints that, because the question states: (the number corresponds to the accumulated summation over the successive indexes). My problem is creating the function that does so keeping track of the indexes. Any guidance would be great. Thanks again in advance.

count_indexes = ?
print_statement = count_indexes + 1
for i in range(0,11,count_indexes):
    print("Hello",print_statement)

The expected result should print hello 5 times, each on different lines, each with different numbers on them, and the numbers should be 0,1,3,6,10.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
177 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 = 0
for i in range(5):
    cum_idx += i
    print(f'Hello {cum_idx}')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...