Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is this algorithm in Python is printing the result several times?

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?

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 == n:
    print(n, "is a perfect number")
else:
    print(n, " is not a perfect number")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading