Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 全局变量计数器不会改变_Python 2.7_Global - Fatal编程技术网

Python 2.7 全局变量计数器不会改变

Python 2.7 全局变量计数器不会改变,python-2.7,global,Python 2.7,Global,我有我正在处理的代码,我遇到的问题是,当程序将第一个字符添加到列表中时,它不会将counter更改为counter=counter+1 import random import string global counter counter = 0 def diceroll(): roll = random.randint(1,6) return roll def codegen(dice,counter): if dice in [1,3,5]: li

我有我正在处理的代码,我遇到的问题是,当程序将第一个字符添加到列表中时,它不会将counter更改为counter=counter+1

import random
import string

global counter
counter = 0

def diceroll():
    roll = random.randint(1,6)
    return roll

def codegen(dice,counter):
    if dice in [1,3,5]:
        list1[counter] = str(random.randint(0,9))
        counter = counter + 1
        if counter in [6,12,18,24]:
            counter = counter + 1
        else:
            pass
    elif dice in [2,4,6]:
        list1[counter] = random.choice(string.ascii_uppercase)
        counter = counter + 1
        if counter in [6,12,18,24]:
            counter = counter + 1
        else:
            pass

list1 = ["-","-","-","-"]

print "Welcome to the Microsoft Code Generator"
ent = raw_input("\nPlease press Enter to generate your 25 character code: ")

while ent != "":
    print "\nYou did not press Enter"
    ent = raw_input("\nPlease press Enter to generate your 25 character code: ")

while len(list1) != 29:
    dice = diceroll()
    codegen(dice,counter)
else:
    print list1
因为您将计数器作为参数传递,所以这是对全局变量的阴影。如果要使用全局变量,请不要将其作为codegen函数的参数

def codegen(dice):
    if dice in [1,3,5]:
        list1[counter] = str(random.randint(0,9))
        counter = counter + 1
        if counter in [6,12,18,24]:
            counter = counter + 1
        else:
            pass
    elif dice in [2,4,6]:
        list1[counter] = random.choice(string.ascii_uppercase)
        counter = counter + 1
        if counter in [6,12,18,24]:
            counter = counter + 1
        else:
            pass
...

while len(list1) != 29:
    dice = diceroll()
    codegen(dice)
else:
    print list1

若要在函数中使用全局变量,若要赋值,必须将其声明为全局变量。例如:

count = 0

def foo():
  global count
  count += 1
  print count
调用foo 3次,然后检查count将导致以下结果

foo()
> 1
foo()
> 2
foo()
> 3
count
> 3

如您所见,将count声明为全局让我们增加它。在函数中将变量声明为全局变量,不要将其作为参数传递为全局变量,这样就不需要这样做了。

哦,是的,我明白,这是有道理的,我忘记了你可以使用增量而不是较长的重新分配方法,这给我带来了混乱,谢谢你的帮助,非常感谢:我很高兴这有帮助!这可能是一个棘手的小问题。如果你不介意接受我的答案,假设你在我的帮助下找到了答案,我将不胜感激!虽然,现在我得到一个未绑定的本地错误。这是我更新的代码:是的,你很接近了-你的错误在于全局的位置。在条件之前的codegen函数顶部,键入行全局计数器。现在Python认为您尝试使用的变量计数器是codegen的本地变量,因为您没有在函数中声明它是全局变量。您不需要在顶部设置全局计数器。