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 factors
will not be reset until 0
every 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.