如何访问本地定义的列表(Python)

时间:2015-04-01 23:52:51

标签: python

我试图根据我在函数内创建的列表来检查用户输入。在不使用全局变量的情况下在函数之间传递变量的最佳方法是什么?

def counter():
    integers = []
    x = 0
    while x < 100:
        x = x + 1
        integers.append (x)
        #print integers
    return

integers_global = counter () 
print integers_global
speed = int (raw_input ("what is the speed of an unladen swallow in km/h (enter a number): "))
if speed in integers_global:
    print "the speed of the swallow is equal to", speed, "km/h"
else:
    print "the speed of the swallow is equal to %r" %speed

2 个答案:

答案 0 :(得分:1)

  

在不使用函数的情况下在函数之间传递变量的最佳方法是什么   全局?

参数将值转换为函数,返回值以将其取出。因此,在您的情况下,您只需要解决第二个问题,并且应该将裸return(返回值None)更改为return integers(它返回结果值<强烈的>关心关于! - )。

答案 1 :(得分:0)

显而易见的事情是return您创建的列表。 只需将return语句修改为

即可
 return integers

counter()函数的末尾。

如果你在课堂上使用它们并希望integers多次使用或出于某种原因使用不同的方法,你也可以使它成为self.integers之类的数据属性,但这不是案例在这里。