【发布时间】:2021-04-27 04:48:21
【问题描述】:
这是我在学校的老师给我们的问题:
编写一个 Python 程序以接受整数 N 的值并显示 N 的所有因数。使用用户控制的循环对多个整数重复上述操作。
我对代码的主要部分没有任何问题,但是我不明白如何正确循环它,以便代码再次从头开始运行,直到用户在提示时最后说 N。
这是我的代码:
#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: ")))
我希望代码回到开始并再次请求输入,然后询问用户是否要继续等等。但是当我走到最后时,循环显示了这些结果:
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
如果我输入 y 以外的其他内容,那么它也可以工作,并且仅在循环一次后结束。我希望它无限循环,直到用户给出命令以“y”或“Y”输入停止并在所有其他情况下显示错误消息。
【问题讨论】:
标签: python loops for-loop while-loop factors