我一直收到错误:“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()
答案 0 :(得分:1)
Pitch
行中的Duration
和winsound.Beep(Pitch, Duration)
变量尚未定义。它们与全局范围内的同名变量不同。
为了通知口译员您的Pitch
和Duration
变量与全局范围中定义的变量相同,您需要在函数中使用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()