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

在python中的另一个函数中使用函数中的变量,python,function,return,callable,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"

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

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.")
def投票百分比:
''(字符串)=(浮动)
计算中“是”的子字符串数
字符串结果和字符串中的子字符串数“否”
结果,它应该返回“是”的百分比
前提条件:字符串仅包含是、否和弃权的“”
s=s.下()
s=s.条带()
是=整数(s.count(“是”))
否=整数(s.计数(“否”))
百分比=是/(否+是)
回报率
def投票:
##调用函数
投票率
如果百分比=1.0:##问题在这里出现
打印(“提案一致通过”)
elif百分比>=(2/3)和百分比<1.0:
打印(“提案以绝对多数通过”)
elif百分比<(2/3)和百分比>=.5:
打印(“提案以简单多数通过”)
其他:
打印(“提案失败”)

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

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

所以,在你的投票百分比中,你是返回百分比。这意味着,当你调用这个方法时,你需要把它的结果赋给一个变量

因此,我们将用一个使用您的代码的示例向您展示

从这里查看您的代码:

def vote(s):
    ##Calling function
    vote_percentage(s)
调用vote_percentage时需要做的是存储返回值,因此可以执行以下操作:

percentage = vote_percentage(s)
def boo():
    x = foo()
现在,在可变百分比中,您实际上有了投票返回百分比

下面是另一个小示例,可以为您进一步解释范围:

如果您这样做:

def foo()
    x = "hello"
def foo():
    x = "hello"
    return x
如果您在方法foo()之外,则无法访问变量x。它仅在foo的“范围”内。因此,如果您这样做:

def foo()
    x = "hello"
def foo():
    x = "hello"
    return x
还有另一个方法需要foo()的结果,您没有访问该“x”的权限,因此需要将该返回存储在如下变量中:

percentage = vote_percentage(s)
def boo():
    x = foo()

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

将返回值赋给变量:
percentage=vote\u percentage
谢谢。这解决了问题。@Stephanie不客气。你应该接受答案,以便帮助下一个有类似问题的人