从另一个布尔函数检查

2024-09-30 06:25:05 发布

您现在位置:Python中文网/ 问答频道 /正文

当另一个函数的布尔值设置为“True”时,我正在尝试做一些事情。我尝试过使用return(variable),但是当涉及到请求bool的函数时,它总是说False。在问这个之前我看了一下这里,因为我觉得这似乎是很基本的东西。但我找不到有用的东西。我希望有人能帮我。 这是我的密码。在

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

Tags: 函数falsetrue密码returnifisdef
3条回答

首先,不要使用名为bool的变量。它由Python保留,例如str,list,int

其次,bool在全局范围内,因此如果要在函数中编辑它,必须将其定义为global。在

x = 0
bool1 = False

def functionA(x,bool):
    global bool1 #now we have access to bool1 variable which is in global scope
    if x is 0:
        bool1 = True


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



functionA(x,bool1)
functionB(bool1)

print (x, bool1)

输出

^{pr2}$

坚持写代码的方式,你有两个选择。选项1是使用全局变量,确保在要修改的函数中包含global声明:

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

选项2(首选)是实际返回内容,以便将它们传递到其他地方:

^{pr2}$

除此之外,不要使用名称bool,使用x == 0而不是{},functionA可以写成return x == 0,使用if bool:而不是{},使用snake_casefunction_a)而不是{}。在

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.

functionA中的bool的赋值将在functionA中创建一个局部变量;它不会分配给全局变量{}。在

相关问题 更多 >

    热门问题