繁体   English   中英

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

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

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

编写 Python 程序以接受 integer 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: ")))

我想把 go 的代码回到开始并再次要求输入,然后询问用户是否要继续等等。 但是当我走到最后时,循环显示了这些结果:

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循环中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM