This algorithm, which is attached and written below, is printing the result multiple times. It is an algorithm to find out if the received number is a perfect number, that is, if the sum of the divisors of that number results in the number itself, then it is a perfect number. Example: the divisors of 6 are: 3, 2 and 1. Adding 3 + 2 + 1 = 6. Therefore, 6 is a perfect number. The algorithm in Python is this:
number = (int(input("Please, type a number to check if this is a perfect number: ")))
test = 0
for i in range(1, number):
if(number % i == 0):
test = test + i
if test == n:
print(n, "is a perfect number")
else:
print(n, " is not a perfect number")
The error is in the attached file, inside the red rectangle. Please, how to correct this code, so that the correct result is printed?
Becuase you are printing inside for loop and each time when one of your conditions are true it will print the answer.
You should put if and else conditions outside of for loop, like this:
number = (int(input("Please, type a number to check if this is a perfect number: ")))
test = 0
for i in range(1, number):
if(number % i == 0):
test = test + i
if test == number:
print(number, "is a perfect number")
else:
print(number, " is not a perfect number")