如何在 Python 中定义布尔参数

我已经定义了一个函数,它会根据它的值打印一个特定的字符串。但是,我收到一条错误消息,指出global name 'must_print' is not defined.


这是我的代码:


def myfunction(must_print):

    must_print = True

    if bool(must_print) == True:

        print("Done")

    elif bool(must_print) == False:

        print("Change value")


if __name__ == "__main__":

    myfunction(must_print)

你知道我为什么会收到这个错误吗?


慕后森
浏览 171回答 3
3回答

喵喵时光机

定义中名为“must_print”的参数与函数调用的名为“must_print”的参数完全无关。以下代码与您的代码等效:def myfunction(x):    x = True    if bool(x) == True:        print("Done")    elif bool(x) == False:        print("Change value")if __name__ == "__main__":    myfunction(must_print)当 Python 执行代码时,它首先定义函数,然后尝试执行myfunction(must_print).但在那时,还没有定义任何名为“must_print”的东西。参数名称是您定义的函数引用它在调用时传递的值的一种方式 - 函数调用该函数的代码如何拼写该值和名称无关紧要参数的大小与调用代码无关。这意味着您可以孤立地理解函数定义,所以让我们这样做。def myfunction(must_print):    # Replace whatever value must_print had with True    must_print = True    # Convert must_print, which has a boolean value, into a boolean, and compare it to True    if bool(must_print) == True:        print("Done")    # Convert must_print, which has a boolean value, into a boolean, and compare it to False    elif bool(must_print) == False:        print("Change value")用不同的值替换参数的值会使参数变得毫无意义——当你到达if它时将True不管你传递了什么,并且myfunction("Vacation")会像myfunction(False).删除该分配:def myfunction(must_print):    # Convert must_print into a boolean, and compare it to True    if bool(must_print) == True:        print("Done")    # Convert must_print into a boolean, and compare it to False    elif bool(must_print) == False:        print("Change value")但bool(must_print)必须是Trueor False,所以你只需要else一个条件:def myfunction(must_print):    # Convert must_print into a boolean, and compare it to True    if bool(must_print) == True:        print("Done")    else:        print("Change value")现在,如果表达式e是布尔值,e == True则与e.( True == Trueis True, and False == Trueis False.)所以我们可以简化一些:def myfunction(must_print):    # Convert must_print into a boolean    if bool(must_print):        print("Done")    else:        print("Change value")此外,任何 Python 值都被if.也就是说,if bool(e)等同于if e:def myfunction(must_print):    if must_print:        print("Done")    else:        print("Change value")现在剩下的就是调用函数,传递一个合适的参数:if __name__ == "__main__":    myfunction(True)

梵蒂冈之花

你应该重视全局限制。代码:must_print = True    def myfunction(must_print):    global must_print    must_print = True    if bool(must_print) == True:        print("Done")    elif bool(must_print) == False:        print("Change value")if __name__ == "__main__":    myfunction(must_print)输出:Done
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python