2015-10-18 118 views
0

我返回了变量,我仍然得到变量仍然未定义。有人可以帮忙吗?在Python中的另一个函数中的函数中使用变量

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

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

回答

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() 

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

+0

谢谢。这解决了问题。 – Stephanie

+0

@Stephanie欢迎您。你应该接受答案,以帮助有类似问题的下一个人 – idjaw

相关问题