-3

所以这就是我得到的:

x = ['a', 'b', 'c']

y = ['a', 'b', 'c']


def stuff(this, that):
  this = x[randint(0, 2)]
  that = y[randint(0, 2)]
  while this != 'c' or that != 'c'
     print "some %r stuff here etc..." % (this, that)
     this = x[randint(0, 2)]
     that = y[randint(0, 2)] 

stuff(x[randint(0, 2)], x[randint(0, 2)])

当然,这只是程序的“要点”。

所以一切都很好,就像我想要的那样,直到这部分结束。我遇到的问题是,当我尝试在全局范围内打印或使用成功的 while 循环的最终结果时,我显然得到了一个 NameError,当我尝试将全局添加到函数内的变量时,我得到 SyntaxError: name ' blah' 是全球性和本地性的。如果我在函数外部创建随机变量,那么我打印出来的是那个变量,而不是满足 while-loop 语句的那个​​变量。

现在我知道我可以将 print 放入函数中,但这只是重复上述基本步骤的更大程序的一部分。我想将总结果一起打印出来:

print "blah blah is %r, and %r %r %r etc.. blah blah.." % (x, y, z, a, b, etc)

如何解决这个问题,以便我可以准确地收集满足 while 循环的变量并在整个程序的其他部分使用它们?PS:对不起,我还处于学习阶段..

4

1 回答 1

3

使用return语句将结果返回给调用者。这是传递变量的首选方式(global并不理想,因为它会使全局命名空间变得混乱,并且可能会在以后产生名称冲突问题)。

def pick_random(x, y):
    return random.choice(x), random.choice(y)

this, that = pick_random(x, y)

如果你想继续从函数中产生值,你可以使用yield

def pick_random(x, y):
    while True:
        this, that = random.choice(x), random.choice(y)
        if this == 'c' and that == 'c':
            return
        yield this, that

for this, that in pick_random(x, y):
    print this, that
于 2013-02-23T19:42:41.433 回答