I'm a rank beginner in Python, and I am working my way through various relevant OpenCourseware modules. In response to the prompt
Write a procedure that takes a list of numbers, nums, and a limit, limit, and returns a list which is the shortest prefix of nums the sum of whose values is greater than limit. Use for. Try to avoid using explicit indexing into the list.
I wrote the following simple procedure
def numberlist(nums,limit):
sum=0
i=0
for i in nums:
sum=sum+i
if sum>limit:
return i
else:
print i
It gets the job done, but the division of labor between if and else seems inelegant, as does the use of both return and print. Is there a better way to structure this basic loop?