As many others pointed out, when the return statement executes, your function will finish, and will not continue looping. However, you have options for returning multiple values from a single function. For example aggregating your values in a list and return that, or to use the yield
keyword instead of return
. The yield
keyword will make your function a generator function, which returns an iterable generator object with all your expected elements.
I advise you to split your code into separate functions, so you have the original formula as a function of i, and a generator function which will return the elements for 1 <= i < n
. Note that you can collect the elements of a generator to a list by supplying it to the list
constructor.
def pyg(i):
a = (2*i) + 1
b = (2*i) * (i+1)
c = (2*i) * (i+1) + 1
return (a,b,c)
def pygs(n):
for i in range(1, n):
yield pyg(i)
print(list(pygs(10))) # prints the first 9 Pythagorean triplet as a list of tuples