2013-02-23 40 views
-3

所以這是我得到:嗨,我如何使這個隨機生成的局部變量的最終結果變成一個全局變量? Python的

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:名字'blah'是全球性和地方性的。 如果我在函數外創建隨機變量,那麼我打印出來的就是這個變量,而不是滿足while循環語句的那個​​變量。

現在我知道我可以在功能中打印,但這只是一個較大的 程序,它重複上述基本步驟。我想打印的總結果一起出去 像這樣:

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

如何解決這個問題,所以我可以準確地收集滿足while循環,並在整個程序的其它部分使用它們的變量? PS:對不起,我仍處於學習階段。

+0

使用'random.choice(X)的''而不是X [random.randint(0 ,2)]'。 – 2013-02-23 19:42:39

+0

只需在函數頂部聲明它們爲「全局」。 – martineau 2013-02-23 19:55:58

+0

RTFM! '全球'變量將成爲你的朋友。 – Mic 2013-02-23 19:58:42

回答

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