Python 如何让用户退出while循环
我正在尝试一段时间的循环搜索,但随后我让用户输入5退出循环。我在python 3中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:
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
命令中断“最低级别循环”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