为什么这个for循环给我一个不正确的输出?

4 python for-loop if-statement python-3.x

我有一个函数告诉我一个数字的因素,然后应该打印它有多少.

factors = 0

def getFactors(n):
    global factors
    for i in range(1,n):
        if n%i==0:
            print(i)
            factors += 1
    print(n, "has", factors, "factors.")
Run Code Online (Sandbox Code Playgroud)

但是,因素的数量似乎是错误的.显然16有6个因素,即使它清楚地列出了4个.

>>> getFactors(16)
1
2
4
8
16 has 6 factors.
>>> 
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?

Cor*_*mer 5

在你第一次打电话时,getFactors(16)你会正确得到4.问题可能是您多次调用该函数,并且自您使用以来global factors,每次调用函数时factors都不会重置该值0.每次调用函数时,全局变量都会不断变异.

如果删除global变量并使其在本地运行,它将正常工作

def getFactors(n):
    factors = 0
    for i in range(1,n):
        if n%i==0:
            print(i)
            factors += 1
    print(n, "has", factors, "factors.")

>>> getFactors(16)
1
2
4
8
16 has 4 factors.
Run Code Online (Sandbox Code Playgroud)