Skip to main content
 首页 » 编程设计

python之从函数内更改全局变量

2024年10月25日8linjiqin

只是为了练习,我正在尝试重新创建游戏 Dudo在 Python 中(我认为游戏知识对我的问题影响不大)。基本上,六个玩家有一定数量的骰子(由 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 

每个玩家都有一个包含六个数字的列表,代表他们拥有的每个骰子(敌人 1、敌人 2 等)。所以我使用循环遍历每个列表索引以找到数字 1,然后根据它更新总数。当我运行该函数时,它会正确打印总数。但是,如果我告诉它打印 num1(在函数之外),它会告诉我 0,这意味着我的函数没有正确地将 num1 更改为总计。有谁知道我做错了什么?

谢谢!

请您参考如下方法:

告诉程序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