Home > Back-end >  Python function with multiple input use result from another function with multiple input
Python function with multiple input use result from another function with multiple input

Time:02-28

I am trying to define two functions in python where one function is inside another function. Both function gets input separately and have different calculation.

Below is code example

def calc_one(x,y):

output_one = x*2 
output_two = y*4

    def calc_two(x1,y1):
        global output_one
        global output_two
    
        output_three = output_one * x1
        output_four = output_two * y1
        calc_two()

calc_one(calc_two(output_four)*x/output_one, calc_two(output_three)*y/output_two) ## Here I want to get output from function by giving separate 
                                       input so that I get result from calc_one()

I have inserted global input so that it can be used from first function.

Please advise how can I correct this code?

Thank you for your time.

Best Regards,

CodePudding user response:

I'm not sure what you are trying to achieve by this, but I think it's not possible for the sake of scoping rules in Python. You could make a class though, pass the values to an instance and then do some operations on it:

class Calc(object):
    def __init__(self, x, y):
        self.output_one = x
        self.output_two = y

    def calc_one(self, x1, y1):
        self.output_one = self.output_one * x1
        self.output_two = self.output_two * y1
        return (self.output_one, self.output_two)

c1 = Calc(2, 3)             

(x, y) = c1.calc_one(5, 6)

CodePudding user response:

If it doesn't have to be a nested function you could do this with a single function, for loop, and a list.

variable_name_list = ['x1','x2','x3','x4']

def input_function():
    variable_list = dict()
    for i in variable_name_list:
        n = input(f"Enter number for {i}: \n")
        variable_list[i] = n

    for x in variable_list:
        a1 = int(variable_list['x1']) * 2
        a2 = int(variable_list['x2']) * 2
        a3 = int(variable_list['x3']) * a1
        a4 = int(variable_list['x4']) * a2

    return a3,a4

Run the function and then just unpack the variables to be used or printed.

a3, a4 = input_function()

print(a3, a4)

CodePudding user response:

To do a function in a function, you can do it like that:

def example(p1,p2):
    f = p1   7
    def example2(p11,p22):
        global f
        f2 = f   7
        .....
  • Related