UnboundLocalError:局部变量“x”

2022-01-18 23:53:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个初级程序来更好地理解python编程。一个简单的while true循环,将值1加到X,并根据X小于或大于10打印“help”或“doing something”;然后当x大于20时中断。我还试图添加一个键盘中断来中断循环,如果它不是太复杂的话。。如果有任何提示帮助,我会出错

Traceback (most recent call last):
  File "so.py", line 23, in <module>
    help()
  File "so.py", line 11, in help
    x += 1
UnboundLocalError: local variable 'x' referenced before assignment

代码:

import time

x = 1

try:

    def help():

        print("Help.")
        time.sleep(2)
        x += 1


    def doStuff():

        print("Doing Stuff")
        time.sleep(2)
        x += 1

    while True:

        if x < 10:
            help()
        elif x < 20 and x > 10:
            doStuff()
        else:
            break

except KeyboardInterrupt:
    exit()