在python中的另一个函数中使用函数中的变量

时间:2015-10-18 14:09:48

标签: python function return callable

我返回了变量,我仍然得到变量仍未定义。有人可以帮忙吗?

def vote_percentage(s):
    '''(string) = (float)
    count the number of substrings 'yes' in
    the string results and the number of substrings 'no' in the string
    results, and it should return the percentage of "yes"
    Precondition: String only contains yes, no, and abstained'''
    s = s.lower()
    s = s.strip()
    yes = int(s.count("yes"))
    no = int(s.count("no"))
    percentage = yes / (no + yes)
    return percentage

def vote(s):
    ##Calling function
    vote_percentage(s)
    if percentage == 1.0: ##problem runs here
        print("The proposal passes unanimously.")
    elif percentage >= (2/3) and percentage < 1.0:
        print("The proposal passes with super majority.")
    elif percentage < (2/3) and percentage >= .5:
        print("The proposal passes with simple majority.")
    else:
        print("The proposal fails.")

1 个答案:

答案 0 :(得分:0)

根据您实现代码的方式,如果在一个方法中定义变量,则无法在另一个方法中访问它。

vote_percentage中的百分比变量仅在vote_percentage方法的范围内,这意味着它不能像您尝试使用它一样在该方法之外使用。

因此,在您的vote_percentage中,您将返回百分比。这意味着,当您调用此方法时,您需要将其结果实际分配给变量。

因此,使用您的代码向您展示一个示例。

从这里查看您的代码:

def vote(s):
    ##Calling function
    vote_percentage(s)

调用vote_percentage时你需要做的是实际存储返回值,所以你可以这样做:

percentage = vote_percentage(s)

现在,您确实在变量百分比中返回了vote_percentage。

这是另一个为您进一步解释范围的小例子:

如果你这样做:

def foo()
    x = "hello"

如果你在方法foo()之外,则无法访问变量x。它只在foo的“范围”内。所以,如果你这样做:

def foo():
    x = "hello"
    return x

你有另一个方法需要foo()的结果,你没有访问那个“x”,所以你需要将这个返回存储在这样的变量中:

def boo():
    x = foo()

正如你在我的例子中看到的,类似于你的代码,我甚至在boo()中使用了变量x,因为它是一个“不同的”x。它与foo()不在同一范围内。