I have a function that tells me the factors of a number, then should print how many 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 to be wrong. Apparently 16 has 6 factors even though it clearly lists 4.
>>> getFactors(16)
1
2
4
8
16 has 6 factors.
>>>
What have I done wrong here?
1 Answer 1
On the first time you call getFactors(16) you will correctly get 4. The problem is likely that you've called the function multiple times, and since you used global factors, the value of factors isn't reset to 0 each time you call the function. The global variable keeps being mutated each time you call the function.
If you remove the global variable and make it function local it will work fine
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.
2 Comments
return [i for i in range(1,n) if n%i == 0] (or use yield, of course)
n. Obviously, a factor cannot be greater thann/2. Thus you can spare a half of iterations withrange(1, n/2)