从代码开始循环,直到用户说停止在 Python

Loop from the start of the code until the user says stop in Python

这是我学校老师给我们的问题:

编写一个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' 输入停止并在所有其他情况下显示错误消息。

我通过将您的内部 while 循环移动到 else 案例来解决您的问题。此外,在 if 语句 N == 'Y' 中,我再插入一个 N = input(...) 命令:

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()

结果:

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
>>>
  • 旁注:运行 Python 3.9.1,Window 10.
  • 也许您希望将相同的 try-catch 块包含到用户控制的 while 循环中。