This is the question my teacher at school has given us:
Write a Python program to accept the value of an integer N and display all the factors of N. Repeat the above for multiple integers using a user-controlled loop.
I'm not having any trouble with the main part of the code, however i don't understand how to loop it properly so that the code runs through the beginning again till the user says N at the end when prompted.
This is my code:
#this is the main part of the code
def print_factors(x):
print("The factors of",x,"are: ")
for i in range(1,x+1):
if x%i==0:
print(i)
#this is the error handling part of the code
while True:
try:
n=int(input("Please enter a number: "))
except ValueError:
print("Please enter a valid number.")
continue
else:
break
print_factors(n)
#this is the looping part where i am having trouble
N = input("Do you want to continue to find factors Y/N: ").upper()
while True:
while N not in 'YN':
if N == 'Y':
print_factors(int(input("Enter a number: ")))
elif N == 'N':
break
else:
print("Invalid input, please try again.")
N = input("Do you want to continue to find factors Y/N: ").upper()
print_factors(int(input("Enter a number: ")))
I want the code to go back to the start and ask for input again, and then ask if the user wants to continue and so on. But when I got to the end, the loop shows these results:
Do you want to continue to find factors Y/N: e
Invalid input, please try again.
Do you want to continue to find factors Y/N: y
Enter a number: 42
The factors of 42 are:
1
2
3
6
7
14
21
42
If I type something other than y, then it also works, and ends after looping only once. I want it to loop endlessly till the user gives the command to stop with a 'y' or 'Y' input and show an error message in all other cases.
I solve your problem by moving your inner while
loop into the else
case. Also, in the if
statement N == 'Y'
, I insert one more N = input(...)
command:
N = input("Do you want to continue to find factors Y/N: ").upper()
while True:
if N == 'Y':
print_factors(int(input("Enter a number: ")))
N = input("Do you want to continue to find factors Y/N: ").upper()
elif N == 'N':
break
else:
while N not in 'YN':
print("Invalid input, please try again.")
N = input("Do you want to continue to find factors Y/N: ").upper()
Result:
Please enter a number: 15
The factors of 15 are:
1
3
5
15
Do you want to continue to find factors Y/N: y
Enter a number: 23
The factors of 23 are:
1
23
Do you want to continue to find factors Y/N: e
Invalid input, please try again.
Do you want to continue to find factors Y/N: y
Enter a number: 32
The factors of 32 are:
1
2
4
8
16
32
Do you want to continue to find factors Y/N: n
>>>
try-catch
block into the user-controlled while
loop.