Python:UnboundLocalError:赋值前引用的局部变量'n'

时间:2015-12-21 18:57:43

标签: python python-3.x

我一直收到错误:“UnboundLocalError:在分配之前引用的局部变量'Pitch'有没有办法解决这个问题?

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()

2 个答案:

答案 0 :(得分:1)

Pitch行中的Durationwinsound.Beep(Pitch, Duration)变量尚未定义。它们与全局范围内的同名变量不同。

为了通知口译员您的PitchDuration变量与全局范围中定义的变量相同,您需要在函数中使用global关键字:< / p>

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

此外,您应该 defintely 重命名您的函数,并避免使用与Python库中相同的名称命名您的函数。

答案 1 :(得分: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()