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() |
为了通知解释器您的
1 2 3 4 | def random(): global Pitch, Duration # <<--- this resolves your scoping issue winsound.Beep(Pitch, Duration) Pitch = random.randint(1000, 10000) |
另外,您应该明确地重命名您的函数,避免使用与Python库中的函数相同的名称来命名函数。
使用
1 2 3 | def random(): global Pitch, Duration ... |
但是,请看一下您用函数
请将函数重命名为
还可以使用循环:
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() |