Python functions passing and returning multiple values example | applied electronics engineering


Python functions passing and returning multiple values example

By Applied Electronics - Tuesday, July 19, 2016 No Comments
Python functions are one of the easiest and coolest thing in python. Compared to other programming language they are really easily to write and get used to.

Here we show how to pass multiple values to a function and return multiple values from a python function.

First let see how to write python function code that returns multiple values. Consider that you have a function y w.r.t x and the derivative y1 also w.r.t x as follows:

 We can write a function called fcn( ) which takes one parameter which is x and returns the value of y(x) and y1(x). Thus we return multiple(two) values from the function fcn( ).

We write this in python as follows:

def fcn(x):
    y = 2*x**2 + x
    y1 = 4*x + 1
    return y,y1

Now we can check this as follows in the command line(or if you want to code it in the script file).

Out: (171, 37)

That is we pass 9 as x into the function argument and we get a tuple of 171 and 37. That is y(9) is 171 and y1(9) is 37.

So in order to return multiple values in python, we just write and calculate what we want to return and then in the return line we append the variable names, in this case y and y1.

Now, passing multiple values to a python function is also very easy to do. For sake of example we modify the equation above which is as follows:

In this case, we have y(x) depending on three values a, b and x itself. a and b are constant. The y1(x) is the derivative of y(x) as you know from elementary calculus class.

We can now write a function that takes in the input x, a, b and returns y(x) and y1(x). The python code for this is as follows:

def fcn(x, a, b):
    y = a*x**2 + b*x
    y1 = 2*a*x + b
    return y,y1

Now we can use the function fcn( ) by passing in the values of x, a and b as follows:

Out: (171, 37)

So in this way you can return any number of values from a python function and pass in any number of parameters as the arguments of the python function.

No Comment to " Python functions passing and returning multiple values example "