Python 如何让用户退出while循环

Python 如何让用户退出while循环,python,Python,我正在尝试一段时间的循环搜索,但随后我让用户输入5退出循环。我在python 3中 def main(): print("Welcome to the List Info Checker") printMenu() printValue = input("Please enter a number between 1 and 5(inclusive): ") while printValue != 5: if printValue == 1:

我正在尝试一段时间的循环搜索,但随后我让用户输入5退出循环。我在python 3中

def main():
    print("Welcome to the List Info Checker")
    printMenu()
    printValue = input("Please enter a number between 1 and 5(inclusive): ")
    while printValue != 5:
        if printValue == 1:
            print("1")
        elif printValue == 2:
           # allTheSame()
            print("2")
        elif printValue == 3:
           # allDifferent()
            print("3")
        elif printValue == 4:
           # sortThis()
            print("4")

main()

您需要在循环中提示输入,否则它总是检查第一次输入的相同值。试试这个:

def main():
print("Welcome to the List Info Checker")
printMenu()
printValue = input("Please enter a number between 1 and 5(inclusive): ")
while printValue != 5:
    if printValue == 1:
        print("1")
    elif printValue == 2:
       # allTheSame()
        print("2")
    elif printValue == 3:
       # allDifferent()
        print("3")
    elif printValue == 4:
       # sortThis()
        print("4")
    printValue = input("Please enter a number between 1 and 5(inclusive): ")

main()

有两种方法可以打破
while
循环

  • 以某种方式更改语句,使其不再为
    True

  • 使用
    break
    命令中断“最低级别循环”

  • 因为用户输入只在循环开始之前被询问,所以在循环开始后它不可能改变,从而导致无休止的循环。如果输入在循环内,则用户可能会在输入5时中断输入,因为每次循环重新启动时都会询问输入:

    printValue = input("Please enter a number between 1 and 5(inclusive): ")
    
    while printValue != 5:
    
        if printValue == 1:
            print("1")
        elif printValue == 2:
           # allTheSame()
            print("2")
        elif printValue == 3:
           # allDifferent()
            print("3")
        elif printValue == 4:
           # sortThis()
            print("4")
    
        printValue = input("Please enter a number between 1 and 5(inclusive): ")
    
    你可以用“break”

    还是最后两行

        else:
            break
    

    这是Python3还是Python2?@Whud在下面解释。此外,如果您陷入无限循环,并且想要停止程序,您可以使用中断键
    ctrl-c
        else:
            break