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

Python: UnboundLocalError: local variable 'n' referenced before assignment

本问题已经有最佳答案,请猛点这里访问。

我一直得到错误:"unboundlocalerror:local variable‘pitch’referenced before assignment"有什么方法可以解决这个问题吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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()


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

为了通知解释器您的PitchDuration变量与全局范围中定义的变量相同,您需要在函数中使用global关键字:

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

另外,您应该明确地重命名您的函数,避免使用与Python库中的函数相同的名称来命名函数。


使用global

1
2
3
def random():
    global Pitch, Duration
    ...

但是,请看一下您用函数random()重新定义了模块random

请将函数重命名为random_func()

还可以使用循环:

1
2
3
4
5
6
7
8
9
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()