【问题标题】:Loop from the start of the code until the user says stop in Python从代码开始循环,直到用户说在 Python 中停止
【发布时间】: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


    【解决方案1】:

    我通过将您的内部 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 循环中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      • 2014-01-21
      • 1970-01-01
      • 2011-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多