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()
CodePudding user response:
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:
...
CodePudding user response:
From the problem description, I assume that the program should terminate after the perfect number is found. There are two things which can be added, a loop to go over the input prompt each time the user feeds a number and a break condition after finding the perfect number. Here's one implementation which works.
def main():
while True:
num = int(input("Enter a perfect integer: "))
if isPerfect(num) == False:
num = int(input(f"{num} is not a perfect number. Re-enter: "))
isPerfect(num)
elif isPerfect(num) == True:
print("Congratulations! ",num, ' is a perfect number.')
break