如何增加函数中的全局变量,并在Python中多次使用/递增

2024-09-26 18:18:51 发布

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

我有2个Python文件:

函数.py

global counter
counter = 0

def printC():
    print(counter)

def increaseC():
    counter += 1

和amain.py

from functions import printC
from functions import increaseC

printC()
increaseC()

第一个函数打印0时没有问题,但随后我收到错误消息:

计数器+=1
UnboundLocalError:赋值前引用的局部变量“counter”

我的问题是:如何增加全局变量,而不是像这样打印:

from functions import printC
from functions import increaseC

printC()
increaseC()
printC()

要获得具有1个值的第二次打印


Tags: 文件函数frompyimport消息def错误

热门问题