【问题标题】:How to make my program stop running when I press a certain key当我按下某个键时如何让我的程序停止运行
【发布时间】:2020-07-22 07:48:49
【问题描述】:

我的程序正在制作一个计算器,我选择了重新启动。基本上,如果用户想继续,他按“y”,如果他不想继续,他按随机字母或某个字母。那么您能否帮助我了解如何通过按随机键或特定键来让一个人停止运行我的程序。

这是我的代码:

def main():
num1 = float(input("Enter first number: "))
operator = input("Enter operator: ")
num2 = float(input("Enter second number: "))

if operator == "+":
  print(num1 + num2)
elif operator == "-":
  print(num1 - num2)
elif operator == "*":
  print(num1 * num2)
elif operator == "/":
  print(num1 / num2)
else:
    print("Error: Invalid operator")

restart = input("Do want to continue? Press \"y\" to continue or press any key to end ")
if restart == "y" or "Y":
    print("")
    main()

main()

编辑:exit() 和导入系统方法不起作用

【问题讨论】:

  • if restart == "y" or "Y": 可以简化为 if restart.lower() == 'y':

标签: python


【解决方案1】:

使用 sys.exit()。在你的代码顶部像这里

    import sys

比在代码的最后部分实现退出部分

    restart = input("Do want to continue? Press \"y\" to continue or press any key to 
    end ")
    if restart == "y" or restart == "Y":
        print("")
        main()
    else:
        print("shutting down")
        sys.exit()

【讨论】:

  • 试过了,但是当我输入随机字母时它并没有停止运行
【解决方案2】:
import sys

...

if restart == "y" or "Y":
    print("")
    main()
else:
    sys.exit()

当用户提供除yY 以外的输入时,您可以使用sys 模块中的退出函数退出。

【讨论】:

  • 试过了,但是当我输入随机字母时它并没有停止运行
【解决方案3】:

试试这个代码

import sys
def main():
    num1 = float(input("Enter first number: "))
    operator = input("Enter operator: ")
    num2 = float(input("Enter second number: "))

    if operator == "+":
        print(num1 + num2)
    elif operator == "-":
        print(num1 - num2)
    elif operator == "*":
        print(num1 * num2)
    elif operator == "/":
       print(num1 / num2)
    else:
        print("Error: Invalid operator")

restart = input("Do want to continue? Press \"y\" to continue or press any key to end ")
if restart.lower() == "y":
    print("")
    main()
else:
    sys.exit()

【讨论】:

  • 试过了,但是当我输入随机字母时它并没有停止运行
【解决方案4】:

它应该是这样工作的:

a = input('Press a key to exit')
if a:
    exit(0)

在您的代码中,您可以添加 else 条件并将 exit() 方法放入其中。

【讨论】:

  • 试过了,但是当我输入随机字母时它并没有停止运行
  • 请记住,使用 input() 函数需要您在进入下一行代码之前按 enterr。另外,我的代码有错误,对不起,我更新了它
猜你喜欢
  • 2012-12-22
  • 2014-04-26
  • 1970-01-01
  • 2011-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-22
相关资源
最近更新 更多