函数不修改python中的变量

2024-05-29 06:43:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了两个列表,a,b和10个从0到61的随机数,然后比较这些列表是否有公共数。你知道吗

我把普通号码存储在一个单独的列表中。你知道吗

如果列表中确实有数字,则commonCount将上升,如果列表为空,则noCommonCount将上升。你知道吗

但是当我要打印计数时,在我将函数随机10次之后,它会打印出0。你知道吗

我不知道为什么,因为我在函数外声明了变量commonCount和noCommonCount。你知道吗

import random

noCommonCount = 0
commonCount = 0

def list_overlap():
    a = []
    b = []

    count = 0

    while count < 10:
        count = count + 1
        a.append(random.randint(0, 61))
        b.append(random.randint(0, 61))    

    commonNumbers = []

    for i in a:
        if i in b:
            if i not in commonNumbers:
                commonNumbers.append(i)

    if not commonNumbers:
        noCommonCount + 1
    else:
        commonCount + 1


functionCount = 0

while functionCount < 10:
    functionCount = functionCount + 1
    list_overlap()

print(noCommonCount)
print(commonCount)

Tags: 函数in列表ifcountrandomlistrandint
1条回答
网友
1楼 · 发布于 2024-05-29 06:43:42

对于修改在外部作用域上声明的变量的函数,还需要

global variable_name

在函数中是必需的(通常直接在函数声明之后)。你知道吗

相关问题 更多 >

    热门问题