Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

python - 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
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

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

1 Reply

0 votes
by (71.8m points)

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}')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...