Jan-Philipp Koch Jan-Philipp Koch - 5 months ago 9
Python Question

Check boolean from another function

I am trying to do something when a boolean from another function is set to "True". I tried using return(variable) but when it comes to the function that asks for the bool it always says False. I took a look here before asking this because I felt like this seems to be really basic stuff. But i couldn't find anything usefull. I hope someone can help me with this.
Here is my code.

x = 0
bool = False

def functionA(x,bool):
if x is 0:
bool = True


def functionB(bool):
print bool
if bool is True:
print "Halleluhja"



functionA(x,bool)
functionB(bool)

print x, bool

Answer

Sticking to how you've written your code, you have two options. Option 1 is to use a global variable, making sure you include the global declaration in functions where you want to modify it:

x = 0
bool = False

def functionA(x):
    global bool
    if x is 0:
        bool = True

def functionB():
    print bool
    if bool is True:
        print "Halleluhja"

functionA(x)
functionB()

print x, bool

Option 2 (preferred) is to actually return things so that they can be passed elsewhere:

x = 0

def functionA(x):
    if x is 0:
        return True
    else:
        return False

def functionB(bool):
    print bool
    if bool is True:
        print "Halleluhja"

bool = functionA(x)
functionB(bool)

print x, bool

Other than that, don't use the name bool, use x == 0 rather than x is 0, functionA can be written as just return x == 0, use if bool: rather than if bool is True:, and use snake_case (function_a) rather than camelCase.

Comments