全局变量计数器不会改变

时间:2015-02-13 01:12:03

标签: python-2.7 global

我有这个代码我正在处理,而我遇到的问题是,当程序将第一个字符添加到列表中时,它不会改变计数器来反对"计数器= 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

2 个答案:

答案 0 :(得分:0)

由于您将counter作为参数传递,因此会影响全局变量。如果要使用全局变量,请不要将其作为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

答案 1 :(得分:0)

要在函数中使用全局变量,如果要分配它,则必须将其声明为全局变量。例如:

count = 0

def foo():
  global count
  count += 1
  print count

调用foo() 3次,然后检查count将导致以下

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

正如您所看到的,将count声明为全局让我们增加它。在函数中将变量声明为global将其作为参数传递(全局,因此无论如何都不需要这样做)。