![](/img/trans.png)
[英]How to stop a function & exit program running in a while loop on key press?
[英]How to make my program stop running when I press a certain key
我的程序正在制作一个计算器,我选择了重新启动。 基本上,如果用户想继续,他按“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()
主要的()
编辑:退出()和导入系统方法不起作用
使用 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()
import sys
...
if restart == "y" or "Y":
print("")
main()
else:
sys.exit()
当用户提供除y
或Y
以外的输入时,您可以使用sys
模块中的 exit function 退出。
试试这个代码
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()
它应该像这样工作:
a = input('Press a key to exit')
if a:
exit(0)
在您的代码中,您可以添加 else 条件并将exit()
方法放入其中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.