【问题标题】:Using a variable in a function in another function in python在python中的另一个函数中使用函数中的变量
【发布时间】:2016-01-16 21:11:56
【问题描述】:

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

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.")

【问题讨论】:

  • 将返回值赋值给一个变量:percentage = vote_percentage(s)

标签: python function return callable


【解决方案1】:

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

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() 不在同一范围内。

【讨论】:

  • 谢谢。这解决了问题。
  • @Stephanie 欢迎您。您应该接受答案,以便帮助遇到类似问题的下一个人
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-12
  • 2012-06-06
  • 1970-01-01
  • 1970-01-01
  • 2014-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多