How to Check Whether a Given Number is Perfect Number in Python
In this tutorial, we will learn how to program "How to Check Whether a Given Number Is a Perfect Number in Python." The objective is to determine whether the entered number is a perfect number. This tutorial will guide you step by step through the process of checking for a perfect number. By the end of this tutorial, you will have a solid understanding of how to implement this task effectively in Python, helping you strengthen your problem-solving abilities and improve your coding skills.
This topic is straightforward to understand. Simply follow the instructions provided, and you will be able to complete it with ease. The program will guide you step by step through the process of checking and identifying a perfect number. So, let’s dive into the coding process!
Getting Started:
First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.
Creating Main Function
This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.- while True:
- print("\n============= Check Whether a Given Number is Perfect Number =============\n")
- try:
- n = int(input("Enter any positive integer: "))
- if n <= 0:
- print("Please enter a positive integer greater than 0.")
- continue
- divisors = [i for i in range(1, n) if n % i == 0]
- sum1 = sum(divisors)
- print(f"Divisors of {n} (excluding itself): {divisors}")
- print(f"Sum of divisors = {sum1}")
- if sum1 == n:
- print(f"{n} is a Perfect Number! ✅")
- else:
- print(f"{n} is NOT a Perfect Number ❌")
- except ValueError:
- print("Invalid input. Please enter an integer.")
- continue
- opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
- if opt == 'no':
- print("Exiting program...")
- break
- elif opt != 'yes':
- print("Invalid choice. Exiting program...")
- break
This Python program checks whether a given number is a Perfect Number. It asks the user to enter a positive integer, then finds all its proper divisors (excluding the number itself) and calculates their sum. The program prints both the divisors and their sum, then compares the sum to the original number: if they match, the number is identified as a Perfect Number; otherwise, it is not. It also includes error handling for invalid inputs and ensures the number entered is positive, while giving the user the option to try again or exit.
Output:

There you have it we successfully created How to Check Whether a Given Number is Perfect Number in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
More Tutorials for Python Language