Beginner Python Exercises

Check a Perfect Number

A perfect number equals the sum of its positive divisors excluding itself.

What is Check a Perfect Number?

A perfect number equals the sum of its positive divisors excluding itself.

Check whether proper divisors add up to the number.

When should you use it?

  • Learn Python syntax through a practical example.
  • Build a foundation for larger programming problems.
  • Test an idea quickly without a local setup.

Example code

Run code →
main.py
number = 28
# Proper divisors cannot be larger than half the number.
divisors = [value for value in range(1, number // 2 + 1) if number % value == 0]
result = "is" if sum(divisors) == number else "is not"
print(f"{number} {result} a perfect number")

Expected output

28 is a perfect number

How it works

Only values through half the number can be proper divisors.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the input and predict the output before running.
  2. Handle empty or invalid input.
  3. Wrap the logic in a function and add more test cases.
Run in Python IDE →