Search code examples
pythonpython-3.xfunctionintegeruser-input

How do I get my code to recall upon the function again to start over? (Python)


Here is my code that I am working on. It is supposed to take a number from the user and if its a perfect number it says so, but if its not it asks to enter a new number. When I get to the enter a new number part, it doesn't register my input. Can someone help me out?

def isPerfect(num):
    if num <= 0:                  
        return False
    total = 0                      
    for i in range(1,num):
        if num%i== 0:
            total = total + i
    if total == num:
        return True
    else:
        return False


def main():
    num = int(input("Enter a perfect integer: "))
    if isPerfect(num) == False:
        op = int(input(f"{num} is not a perfect number. Re-enter:"))
        isPerfect(op)
    elif isPerfect(num) == True:
        print("Congratulations!",num, 'is a perfect number.')

if __name__ == '__main__':
   main()

Solution

  • you could just put a while True loop into your main function like so:

    def main():
        first_run = True
        perfect_num_received = False
        while not perfect_num_received:
            if first_run:
                num = int(input("Enter a perfect integer: "))
                first_run = False
            if isPerfect(num) == False:
                num = int(input(f"{num} is not a perfect number. Re-enter:"))
            elif isPerfect(num) == True:
                perfect_num_received = True
                print("Congratulations!",num, 'is a perfect number.')
    

    but also there is already a built in function to check for the data type of a variable so you could just do something like this maybe:

    if type(num) == int:
        ...