2015-12-21 58 views
0

我不斷收到錯誤:「UnboundLocalError:局部變量'在分配前引用的'Pitch'」有沒有解決這個問題的方法?Python:UnboundLocalError:分配之前引用的局部變量'n'

import winsound, random 

Pitch = random.randint(1000, 10000) 
Duration = random.randint(100, 500) 

def random(): 
    winsound.Beep(Pitch, Duration) 
    Pitch = random.randint(1000, 10000) 
    Duration = random.randint(100, 500) 
    winsound.Beep(Pitch, Duration) 
    Pitch = random.randint(1000, 10000) 
    Duration = random.randint(100, 500) 
    winsound.Beep(Pitch, Duration) 
    Pitch = random.randint(1000, 10000) 
    Duration = random.randint(100, 500) 
    winsound.Beep(Pitch, Duration) 
    Pitch = random.randint(1000, 10000) 
    Duration = random.randint(100, 500) 
    winsound.Beep(Pitch, Duration) 

random() 
+0

您需要將它們標記爲全局:「全局音高,持續時間」。另外,如果您要導入模塊「隨機」,請不要將函數命名爲「random」! – senshin

+1

只需在全局範圍刪除那些。看起來他們沒有使用。 – wim

回答

0

使用global

def random(): 
    global Pitch, Duration 
    ... 

還請有你重新定義模塊random與功能random()看看。

請重命名功能,很好,random_func()

您也可以使用循環:

import winsound, random 

def rand_func(): 
    for _ in range(5): 
     Pitch = random.randint(1000, 10000) 
     Duration = random.randint(100, 500) 
     winsound.Beep(Pitch, Duration) 

rand_func() 
0

winsound.Beep(Pitch, Duration)線的PitchDuration變量尚未確定。它們不同於全球範圍內同名變量。

爲了通知解釋,你PitchDuration變量是相同在全球範圍內定義的,你需要使用global關鍵字在你的函數:

def random(): 
    global Pitch, Duration # <<--- this resolves your scoping issue 
    winsound.Beep(Pitch, Duration) 
    Pitch = random.randint(1000, 10000) 

此外,你應該defintely重命名你的函數,並避免用與Python庫中的名稱相同的名稱命名你的函數。

相關問題