How to Find All Perfect Numbers in a Range in Python


In this example, we will learn how to find out all the perfect numbers in a given range in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

lowerLimit = int(input("Please input the lower limit: "))
upperLimit = int(input("Please input the upper limit: "))
print("The Perfect number is: ")
for i in range(lowerLimit, upperLimit + 1):
    sum1 = 0
    for j in range(1, i):
        if i % j == 0:
            sum1 += j
    if  sum1 == i:
        print("{0:6}".format(i), end=" ", sep=" ")
print()

Output:

Please input the lower limit: 1
Please input the upper limit: 30
The Perfect number is:
     6     28

Please input the lower limit: 10
Please input the upper limit: 1000
The Perfect number is:
    28    496
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement