Python call inner function inside another function

1.5k views Asked by At

Edited! I wanted to reference inner function return value outside of outer function, and actually inside of another function.

Example:

def m1():
    def m2():
        x= 'A'
        y= 'B'
        pre_solution = x+y
        return pre_solution
    pre_solution = m2()
    m1_solution = pre_solution*2
    return m1_solution

print(m1())

Now I want to create a new function and I need the return value of m2() to be in it:

def m3():
    pre_solution = m2()
    m3_solution = pre_solution*3
    return m3_solution

print(m3())

I get an error that m2 is not defined. I need to get pre_solution value without using copy and paste(since the real code has many more lines in it). Here is my current work around but I wanted to see if there was an easier way.

def m3():
    x= 'A'
    y= 'B'
    pre_solution = x+y
    m3_solution = pre_solution*3
    return m3_solution

print(m3())

I'm doing it for an assignment that uses autograder and only evaluates code inside of the functions, not the global scope, m1() and m3() are going to be evaluated but if I put m2() into global scope it won't be. Hope it makes sense. It's my very first question on here.

Thank you

1

There are 1 answers

0
Teshtek On

Do you want somthing like this :

def m1():
    def m2():
        m2.var = "Cat" * 2
        return m2.var
    m1.x = m2()
    return m1.x + 'Dog'

m1()

def m3():
    y = m1.x
    z = y * 2
    return z

print(m3())

This method helps you to get the variable inside outer functions.