Check Boolean From Another Function
Solution 1:
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 = 0bool = FalsedeffunctionA(x):
globalboolif x is0:
bool = TruedeffunctionB():
printboolifboolisTrue:
print"Halleluhja"
functionA(x)
functionB()
print x, bool
Option 2 (preferred) is to actually return things so that they can be passed elsewhere:
x = 0deffunctionA(x):
if x is0:
returnTrueelse:
returnFalsedeffunctionB(bool):
printboolifboolisTrue:
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
.
Solution 2:
https://docs.python.org/3.4/tutorial/controlflow.html#defining-functions:
More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.
Your assignment to bool
in functionA
creates a local variable in functionA
; it does not assign to the global variable bool
.
Solution 3:
First of all, do not use a variable named bool
. It's reserved by Python, such as like str,list,int
etc.
Second, bool
is in global scope, so if you want to edit it in a function, you have to define it as global
.
x = 0
bool1 = FalsedeffunctionA(x,bool):
global bool1 #now we have access to bool1 variable which is in global scopeif x is0:
bool1 = TruedeffunctionB(bool):
print (bool1)
ifboolisTrue:
print ("Halleluhja")
functionA(x,bool1)
functionB(bool1)
print (x, bool1)
Output
>>>
True
Halleluhja
0 True
>>>
Post a Comment for "Check Boolean From Another Function"