I know this is probably really basic and there is an easy answer, but I'm not sure how to make two functions call each other. Function A calls Function B on a condition or two, and function B calls function A on a condition or two. Example:
def functionA():
if something is true:
functionB()
if something isn't true:
something is false
def functionB():
if something is false:
functionA()
I am pretty bad at python, so if you answer my question please give me an example or two. I know that I am supposed to put the function before it is called, but I'm not sure how to make it work with two functions. Thanks.
CodePudding user response:
What you've already written will "work".
This isn't C; you can define a function that calls a function that doesn't yet exist, so as long as you don't call such a function until the dependencies exist. As long as neither functionA
nor functionB
is called until both are defined, this "works".
The reason I'm quoting "works" is because as written, this will immediately die with a RecursionError
(the condition for calling each other is the same, so they'd recurse until they hit Python's limit, which you can check by
calling sys.getrecursionlimit()
). But they would be calling each other as requested, you just need to trigger the first one to be called (e.g. by adding a plain functionA()
or functionB()
call after you've defined both of them).
CodePudding user response:
I think one of the most common way to call a function into another function is use callback. It mean you call a function that will call another function you gave it as a parameter. Here is an example :
def sum_numbers(a, b, callback):
res = a b
callback(res)
def print_result(res):
print(res)
sum_numbers(1, 8, print_result)
Output :
9
Here the first function calculate the sum and the second just print the result. But for sure you can do a lot of things more interesting with that.