Why does this give me the wrong conclusion for the loop?

I have a function that tells me about number factors, and then should print how much it has.

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.")

However, the number of factors seems wrong. Apparently, 16 has 6 factors, although 4 are clearly indicated.

>>> getFactors(16)
1
2
4
8
16 has 6 factors.
>>> 

What have I done wrong here?

+4
source share
1 answer

The first time you call getFactors(16), you get it right 4. The problem is probably caused by the function several times, and since you used it global factors, the value factorswill not be reset until 0every time the function is called. A global variable saves a mutation every time you call a function.

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.
+6

Source: https://habr.com/ru/post/1611604/


All Articles