Check Perfect Number in Python
Check whether a number is a perfect number (sum of proper divisors equals the number).
BeginnerConditional ProgramsExample 10 of 20
check-perfect-number.py
1# Program to check perfect number23num = int(input("Enter a positive integer: "))45if num <= 0:6 print("Number must be positive.")7else:8 total = 09 for i in range(1, num):10 if num % i == 0:11 total += i1213 if total == num:14 print(num, "is a perfect number")15 else:16 print(num, "is not a perfect number")
Output
Enter a positive integer: 6 6 is a perfect number
What's going on
A perfect number equals the sum of its positive divisors excluding itself.
We loop from 1 to num-1 and sum divisors to compare with num.
After this program
If the idea is still fuzzy, read Day 8: Conditional Statements in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 conditional programs, or see every topic on Python exercises.