Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function from within another function in Python

I'm starting to learn Python, but I'm having an issue with my code and was hoping someone could help. I have two functions, and I would like to call one function from the other. When I simply tried calling the function, it seemed to be ignored so I'm guessing it's an issue with how I have called it. Below is the snippet of my code in question.

# Define the raw message function
def raw(msg):
    s.send(msg+'\r\n')

    # This is the part where I try to call the output function, but it
    # does not seem to work.
    output('msg', '[==>] '+msg)

    return

# Define the output and error function
def output(type, msg):
    if ((type == 'msg') & (debug == 1)) | (type != msg):
        print('['+strftime("%H:%M:%S", gmtime())+'] ['+type.upper()+'] '+msg)
    if type.lower() == 'fatal':
        sys.exit()
    return

# I will still need to call the output() function from outside a
# function as well. When I specified a static method for output(),
# calling output() outside a function (like below) didn't seem to work.
output('notice', 'Script started')

raw("NICK :PythonBot")

Edited. I am actually calling the raw() function, it was just below the snippet. :)

like image 828
Dead-i Avatar asked Jul 23 '12 22:07

Dead-i


People also ask

Can you call a function inside another function Python?

In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems.

How do you access a function within a function in Python?

Perhaps just calling make_adder() would have been simpler. Incidentally, as you can see, functions are first-class objects in Python. make_adder is an object, and by adding (somearguments) you invoke, or call the function. In this case, that function returns another function object, one that you can call as well.

How do you call a function within a function?

To call a function inside another function, define the inner function inside the outer function and invoke it. When using the function keyword, the function gets hoisted to the top of the scope and can be called from anywhere inside of the outer function.

Can you call functions within other functions?

Calling a function from within itself is called recursion and the simple answer is, yes.


1 Answers

Try simpler case like this:

def func2(msg):
    return 'result of func2("' + func1(msg) + '")'

def func1(msg):
    return 'result of func1("' + msg + '")'

print func1('test')
print func2('test')

It prints:

result of func1("test")
result of func2("result of func1("test")")

Notice the order of function definitions is intentionally reversed. The order of function definitions does not matter in Python.

You should specify better, what does not work for you.

like image 150
pepr Avatar answered Sep 30 '22 10:09

pepr