如何在Python中定义函数定义中的布尔值?

时间:2015-05-19 22:07:39

标签: python variables boolean

我如何定义在函数范围内声明的布尔变量?

我在下面的函数中定义了变量pass = True,并在函数定义中的if语句中设置了它的值:

def test(array, n): # Define the function test with input parameters array and n
    pass = True # Initialize variable pass to the boolean value True
    for i in n: # For n number of times, perform the following operation using i as a counter
        for j in range(i+1,n): # Increment from i+1 to n using j as a counter
        if(array[i] == array[j]):   # If the ith element in array equals the jth element, execute the following code
                                                # If one element is equivalent to any subsequent
                                                # elements of the array, set pass = true
            pass = False # define pass as false

return pass # return pass

1 个答案:

答案 0 :(得分:2)

除了一些缩进问题,我假设是由于在SO上发布而不是由于真正的代码被错误缩进,问题是pass是python中的保留字 - 它是null操作。如果您使用合法标识符(例如shouldPass)替换它,那么您应该没问题:

def test(array, n): # Define the function test with input parameters array and n
    shouldPass = True # Initialize variable shouldPass to the boolean value True
    for i in n: # For n number of times, perform the following operation using i as a counter
        for j in range(i+1,n): # Increment from i+1 to n using j as a counter
            if array[i] == array[j]:   # If the ith element in array equals the jth element, execute the following code
                                                # If one element is equivalent to any subsequent
                                                # elements of the array, set shouldPass = true
                shouldPass = False # define shouldPass as false

    return shouldPass # return shouldPass