如何从python中的函数获取变量

时间:2018-10-01 22:52:12

标签: python python-3.x function

def checkQuota(candidateX_Votes, candidateX_Won):
    quota = int((validVotesCast / (seatsAvaliable + 1)) + 1)

    if candidateX_Votes < quota:
        candidateX_Won = False
        return candidateX_Won

    elif candidateX_Votes >= quota:
        candidateX_Won = True
        return candidateX_Won

目标是将true或false的值设置为函数中放入的变量,例如,如果我执行checkQuota(candidateA_Votes, candidateA_Won),则以后应该可以使用candidateA_Won为其分配true或false的值。

2 个答案:

答案 0 :(得分:1)

由于实际上并没有使用candidateA_Won作为参数,因此我建议您重构为只返回所需的值,并将 that 存储在外部变量中,如下所示:

def checkQuota(candidateX_Votes): # Get rid of the parameter
    quota = int((validVotesCast / (seatsAvaliable + 1)) + 1)

    if candidateX_Votes < quota:
        candidateX_Won = False
        return candidateX_Won

    elif candidateX_Votes >= quota:
        candidateX_Won = True
        return candidateX_Won

然后,您可以使用以下功能:

candidateX_Won = checkQuota(candidateX_Votes) # Without having to pass in a variable

实际上,您甚至可以将以上功能简化为:

def checkQuota(candidateX_Votes):
    return not (candidateX_Votes < int((validVotesCast / (seatsAvaliable + 1)) + 1))

答案 1 :(得分:0)

您的变量candidateX_Won在函数范围内是局部的。当您分配TrueFalse时,您将更改一个局部变量,而不是原始变量。要获得所需的结果,可以使用以下示例:

def checkQuota(candidate_x_votes):
    # here you calculate/get validVotesCast and seatsAvaliable
    quota = int((validVotesCast / (seatsAvaliable + 1)) + 1)
    return not (candidate_x_votes < quota)  # this will return True or False

# and after that you can use your function
candidateX_Votes = 12 # for example 
candidateX_Won = checkQuota(candidateX_Votes)