首页 > 解决方案 > Cannot change the value of global variable in Python

问题描述

I have a function that I want to count how many times it is called (and save a image with that counter value as its name). I made a global function called counter . But if I do counter = counter+1. It says Unresolved reference. Am I missing something ?

Here is the code :

import numpy as np
import cv2
counter = 0
def saveImage(img):
    counter = counter+1

    imgs = str(counter) + '.jpg'
    cv2.imwrite('images/'+imgs, img)

标签: pythonfunctionglobal-variables

解决方案


import numpy as np
import cv2
counter = 0
def saveImage(img):
    global counter  # to modify global variable, you need to explicitly declare so... 
    counter = counter+1

    imgs = str(counter) + '.jpg'
    cv2.imwrite('images/'+imgs, img)

推荐阅读