2017-08-15 172 views
-2

如果這看起來很愚蠢,我真的很抱歉。此代碼導致錯誤:UnboundLocalError:在賦值之前引用的局部變量'current_order',特別是第二個'for'循環的第一行。 如果我將current_order聲明爲全局變量,那麼錯誤是固定的;但是,我仍然不明白爲什麼我必須這樣做。我沒有在第一個for循環中創建變量嗎? (順便說一下,第一個for循環中的條件保證返回True,所以這不是問題)。 非常感謝在函數內部賦值之前引用的局部變量

def choose_pitch_from_order(current_pitch, direction, pitches_in_play, 
chomp_key): 


    for pitch in all_pitches: 
     if current_pitch == pitch.name: 
      current_order = pitch.order 

    for i in current_order: 
     for pitch in pitches_in_play: 
      if pitch.index == i: 
       next_set = pitch 
       pitches_in_play.remove(next_set) 
       return (next_set, direction, chomp_key) 
+1

如果'如果current_pitch == pitch.name'永遠不會計算爲'True'會發生什麼? –

+0

@JonathonReinhart他聲稱永遠不會發生。 – Barmar

+1

...或者'all_pitches'是空的。 –

回答

2

這似乎是你的第一個循環將不會執行中的條件,因爲current_pitch是不是在任何時候等於pitch.name,所以current_order從未分配。如果是這種情況,您需要在外部定義current_order,並使用一些默認值,以便此代碼不會失敗。

def choose_pitch_from_order(current_pitch, direction, pitches_in_play, 
chomp_key): 
    current_order = [] # default value, declaration outside loop/condition 
    ... 

記住,默認值必須是某種迭代(列表,元組,集合或其他任何可迭代),否則一個TypeError將在第二循環中拋出。

+0

他寫道**順便說一句,第一個for循環中的條件保證返回True,所以這不是問題**。但是我懷疑你是對的,他錯了。 – Barmar

+0

@Barmar同意,除非OP的代碼與此處顯示的代碼不同,否則沒有其他原因會導致此錯誤出現。 –

相關問題