n=1
Sum=0
while n<=20:
for i in range(1,n 1):
if(n%i==0):
Sum =i
if(Sum==n):
print(Sum)
n =1
I need to print all the perfect numbers between 1 to 20.
CodePudding user response:
Perfect number is defined here
To achieve that, I would isolate the perfect number check in a function as follows:
def is_perfect(n):
s = 0
for i in range(1,n//2 1):
if(n%i==0):
s = i
return n == s
n=20
print([x for x in range(1, n 1) if is_perfect(x)])
CodePudding user response:
One problem is that you never reset the sum but it should be reset for every new number you try. Otherwise Sum
will grow over n
.
Another issue is, that according to the definition of a perfect number, the number itself is excluded in the division test. But since you run up to n 1
, the number itself will always be added and thus Sum
is always greater than n
.
Third issue is the indentation of the second if
. It will print more often than you expect.
Fixing the code is left as an exercise for the reader. If you want a copy&paste solution, there are probably plenty enough on the Internet.
Besides these primary issues which prevent you from the correct results, the code could be improved in several aspects
- Python coding style: remove the redundant parentheses
- Clean code: naming of the variables
- Reuse: define a method
is_perfect(number)
- Use type hints:
def is_perfect_number(number:int)->bool:
- Performance: division check needs to run until sqrt(n) only.
- Performance: division check could run in steps of 2 once 2 itself has been tested