在函数

时间:2017-08-15 02:43:31

标签: python for-loop

如果这看起来很愚蠢,我真的很抱歉。此代码导致错误:UnboundLocalError:local variable' current_order'在分配之前引用,特别是在第二行的第一行中用于'环。 如果我将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 个答案:

答案 0 :(得分: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
    ...

请记住,默认值必须是某种可迭代的(list,tuple,set或任何其他可迭代的),否则将在第二个循环中抛出TypeError