[Python] Transform code to list perfect numbers from for loop to while loops

Discussão em 'Python' iniciado por Stack, Fevereiro 8, 2025.

  1. Stack

    Stack Membro Participativo

    I am supposed to write a Python program that will identify and print all the perfect numbers in some closed interval [2, n], one per line.

    We only should use nested while loops and if-else statements. I did it somehow using a for loop, but can't figure out the same using a while loop.

    How could I translate my code into a while loop?

    Here's what I have:

    limit = int(input("enter upper limit for perfect number search: "))

    for n in range(2, limit + 1):
    sum = 0
    for divisor in range(1, n):
    if not n % divisor:
    sum += divisor
    if sum == n:
    print(n, "is a perfect number")

    Continue reading...

Compartilhe esta Página