I have an array with a certain number of values, for example M = [1, 2, 3, 4] and a function, where one of the arguments is M. What I need is to get the result of my function when M is 1, when M is 2 etc., basically 4 outputs of the function. What I've tried is to create a for loop and to declare a new variable, for example d = M[i], but I only get the result of the function for the last value in my array M. This is how it looks like:
w = [1, 2, 3, 4]
d = []
def S1(y, x, r, d, t=10):
for i in range(len(w)):
d = w[i]
S = 600*y/(d*t**2) 600*x/(t*d**2)
return S/r-1
Every time I need a different output. First time, I need S/r-1 when w is 1, second time when w is 2 etc.Is there a way to get each value from array M, use it in the function and to get the outputs?
CodePudding user response:
Functions can return multiple values, like this:
def foo(arg):
<do some stuff here>
return x, y, z
The return values will be in the form of a tuple. They can be accessed by indexing:
For example:
returns = foo(arg)
returns[0] -> x
returns[1] -> y
returns[2] -> z
CodePudding user response:
If I'm understanding what you're saying you could do something like this:
def function(M):
answers = []
for i in range(len(M)):
d = M[i]
# insert math here, lets say that it is stored in a variable called "result"
answers.append(result)
return answers
This way, you have a list of the functions outputs with each of the values in M