Reputation: 85
I am supposed to write a function for one of my computer science classes in python. The function is supposed to take in a startValue and then increment it until numberOfValues is reached. This is my function so far:
def nextNValues(startValue, increment, numberOfValues):
result = int(0)
for i in range(0, numberOfValues):
increase = i * increment
result = startValue + increase
return result
I call it by doing:
print(nextNValues(5,4,3))
The problem is that the output is only 13. How do I make it so it returns a number each time it increments. For example, 5, 9, 13? I have been having this problem with my previous functions but I have just been adding and removing things without much logic to get it to work. What am I doing wrong?
Upvotes: 0
Views: 3565
Reputation: 5271
This is a perfect use case for generators.
Long story short, just use yield
instead of return
:
def nextNValues(startValue, increment, numberOfValues):
result = int(0)
for i in range(0, numberOfValues):
increase = i * increment
result = startValue + increase
yield result
The clients of your code can then use it either in a simple loop:
for value in nextNValues(...):
print(value)
Or they can get a list if needed by converting it with list
.
For example, if one needed to print the result:
print(list(nextNValues(...)))
Upvotes: 3
Reputation: 71
def nextNValues(startValue, increment, numberOfValues):
result = []
for i in range(0, numberOfValues):
increase = i * increment
#result = startValue + increase
result.append(startValue + increase)
return result
Upvotes: 0
Reputation: 599956
You should build up a list. Each time through the iteration, append the number to the list. Then, at the end, simply return the list.
Upvotes: 1