从函数中改变全局变量?

时间:2015-04-26 00:15:50

标签: python function variables global

只是为了练习,我试图在Python中重新创建游戏Dudo(我不认为游戏知识会影响我的问题)。基本上,六个玩家有一定数量的骰子(由count1,count2等代表),我需要知道每种骰子的数量(多少1,多少2等)。我创建了一个变量num1(num1 = 0)来表示1的数量,然后我创建了一个函数来查找1的数量。

def find_num1():
    total = 0
    for i in range(you_count):
        if you[i] == 1:
            total = total + 1
    for i in range(count1):
        if enemy1[i] == 1:
            total = total + 1
    for i in range(count2):
        if enemy2[i] == 1:
            total = total + 1
    for i in range(count3):
        if enemy3[i] == 1:
            total = total + 1
    for i in range(count4):
        if enemy4[i] == 1:
            total = total + 1
    for i in range(count5):
        if enemy5[i] == 1:
            total = total + 1
    num1 = total
    print total

每个玩家都有一个包含六个数字的列表,代表他们拥有的每个骰子(enemy1,enemy2等)。因此,我使用循环遍历每个列表索引以查找数字1,然后基于此更新总计。当我运行该功能时,它正确打印总计。但是,如果我告诉它打印num1(在函数之外)它告诉我0,这意味着我的函数没有正确地将num1更改为total。有没有人有任何想法我做错了什么?

谢谢!

2 个答案:

答案 0 :(得分:1)

告诉程序num1是一个全局变量

def find_num1():
    global num1 #Here
    total = 0
    for i in range(you_count):
        if you[i] == 1:
            total = total + 1
    for i in range(count1):
        if enemy1[i] == 1:
            total = total + 1
    for i in range(count2):
        if enemy2[i] == 1:
            total = total + 1
    for i in range(count3):
        if enemy3[i] == 1:
            total = total + 1
    for i in range(count4):
        if enemy4[i] == 1:
            total = total + 1
    for i in range(count5):
        if enemy5[i] == 1:
            total = total + 1
    num1 = total
    print total

答案 1 :(得分:1)

随着程序变得越来越长,拥有太多全局变量将使您的程序难以理解,当您发现错误时难以修复,并且当您想要添加功能时难以改进。幸运的是,有一种简洁的方法可以将函数中的值传递回主程序:return。如果您的最高级别为foo = some_func(),而some_func()return 5结尾,则foo完成后,我们会将{5}分配给some_func()。您可以按如下方式重写:

def find_num1():
    total = 0
    for i in range(you_count):
        if you[i] == 1:
            total = total + 1
    for i in range(count1):
        if enemy1[i] == 1:
            total = total + 1
    for i in range(count2):
        if enemy2[i] == 1:
            total = total + 1
    for i in range(count3):
        if enemy3[i] == 1:
            total = total + 1
    for i in range(count4):
        if enemy4[i] == 1:
            total = total + 1
    for i in range(count5):
        if enemy5[i] == 1:
            total = total + 1
    return total

num1 = find_num1()
print(num1)

你甚至可以通过在函数中创建一个元组并在顶层解包元组来返回多个值:

def sum_and_product(a, b):
    sum_value = a + b
    prod_value = a * b
    return (sum_value, prod_value)

(plusle, times) = sum_and_product(3, 5)
# the function returned (8, 15), and after unpacking,
# plusle is now 8 and times is now 15

另请参阅艰难学习Python 中的return examples

此答案中的代码为双重许可:CC BY-SA 3.0MIT License as published by OSI