如何使用while循环按enter键退出python程序

2024-05-14 18:53:23 发布

您现在位置:Python中文网/ 问答频道 /正文

按enter键时,程序将继续循环

该程序在preesin enter上打印“再见”,然后继续循环返回

按enter键(不使用break)时,如何退出

choice = input("Enter selection:,\n "
               "(X) exit,\n "
               "(1) Celsius to kelvin,\n "
               "(2) celsius to fahrenheit,\n "
               "(3) kelvin to celsius,\n "
               "(4) kelvin to fahrenheit,\n "
               "(5) fahrenhiet to celsius,\n "
               "(6) fahrenheit to kelvin\n")
choice = choice.upper()

while choice[0] != "X" :     
    if choice[0] == '1':
        celsius = input("Enter Celsius(integer), or press enter to exit")
        while celsius:
            celsius = int(celsius)
            #function to convert Celsius to kelvin
            answer = cel_to_kel(celsius)
            print("Kelvin is ", answer)
            celsius = input("Enter celsius, or press enter to exit")
        print("Goodbye")

Tags: ortoanswer程序inputexitpressenter
3条回答

您可以尝试使用:

while 1:
  celsius = input("Enter celsius, or press enter to exit")
  if not celsius:
    break
  #function to convert Celsius to kelvin
  answer = cel_to_kel(int(celsius))
  print("Kelvin is ", answer)

print("Goodbye")

放置一个查看值的if语句:

if celsius == "":
    break

按enter键返回一个带有输入的空字符串,因此使用if语句可以检查它是否为空。在那之后,它就像打破循环一样简单(或者做你想做的其他事情)

问题

问题是您有两个条件不同的循环:

choice = input()
while choice != "X":
    if choice == "1":
        celsius = input()
        while celsius:
            ...
            celsius = input()

一旦用户没有向celsius输入任何内容,内部循环就会停止。但是外部循环一直在运行,因为choice永远不会改变

解决方案“只有一个选择”

如果希望在内部循环完成后退出程序,则可以完全删除外部循环:

choice = input()
if choice == "1":
    celsius = input()
    while celsius:
        ...
        celsius = input()

解决方案“在选择之间切换”

如果要给用户切换到不同转换类型的选项,请在主循环的末尾添加另一个input

choice = input()
while choice != "X":
    if choice == "1":
        celsius = input()
        while celsius:
            ...
            celsius = input()
    choice = input()

解决方案“没有循环的选择”

如果希望用户独立选择每次转换的类型,请删除内部循环:

choice = input()
while choice != "X":
    if choice == "1":
        celsius = input()
        if celsius:
            ...            
    choice = input()

相关问题 更多 >

    热门问题