I try to make a program that print the factors of a number and print its abundant factors. But when im working with it, i found some problem. I don't know why the output is different if i declare a variable named "sum_abundant_factor" inside the for loop and outside the for loop.
"sum_abundant_factor" is a variable that i use to check whether the factor is abundant or not. (abundant number is a number that is smaller than the sum of its proper divisors).
This is my code and output when i declare "sum_abundant_factor" inside the for loop :
input_number = int(input('Input number : '))
factor = ''
sum_factor = 0
abundant_factor = ''
for i in range(1, input_number+1):
if input_number % i == 0:
sum_abundant_factor = 0
factor += str(i) + ' '
if i < input_number :
sum_factor += i
for j in range(1, i):
if i % j == 0:
sum_abundant_factor += j
if sum_abundant_factor > i:
abundant_factor += str(i) + ' '
print('Factors of {} :'.format(input_number), factor)
print('Abundant Factors :', abundant_factor)
Output :
Input number : 54
Factors of 54 : 1 2 3 6 9 18 27 54
Abundant Factors : 18 54
And this is my code and output when i declare "sum_abundant_factor" before (outside) the for loop :
input_number = int(input('Input number : '))
factor = ''
sum_factor = 0
abundant_factor = ''
sum_abundant_factor = 0
for i in range(1, input_number+1):
if input_number % i == 0:
factor += str(i) + ' '
if i < input_number:
sum_factor += i
for j in range(1, i):
if i % j == 0:
sum_abundant_factor += j
if sum_abundant_factor > i:
abundant_factor += str(i) + ' '
print('Factors of {} :'.format(input_number), factor)
print('Abundant Factors :', abundant_factor)
Output :
Input number : 54
Factors of 54 : 1 2 3 6 9 18 27 54
Abundant Factors : 6 9 18 27 54
I have no idea why the abundant factors output is different when i declaring the variable inside and outside for loop. Can anyone help me explain it to me ?
sum_abundant_factorwill be set to 0 initially. With being declared outside of the loop, it will keep its value, and won't be 0 initially. You keep adding to its value, but not reset before each run.