按ENTER键退出Python中不工作的程序
试图让我的代码在按下enter按钮时退出,我遇到了一个按ENTER键退出Python中不工作的程序,python,exit-code,Python,Exit Code,试图让我的代码在按下enter按钮时退出,我遇到了一个ValueError:invalid literal for int(),基数为10:“,但它告诉我我的错误在simulations\u num=int(simulations)行上。有人有主意吗 simulations = input("How many times would you like to run the simulation? ") # Invalid answer, system exit if (no
ValueError:invalid literal for int(),基数为10:“
,但它告诉我我的错误在simulations\u num=int(simulations)
行上。有人有主意吗
simulations = input("How many times would you like to run the simulation? ")
# Invalid answer, system exit
if (not simulations) or int(simulations) <=0:
print("That is not a valid number of simulations.")
print("Shutting down.")
SystemExit
simulations_num = int(simulations)
#the rest of my code comes here
simulations=input(“您希望运行模拟多少次?”)
#回答无效,系统退出
如果(不是模拟)或int(模拟)您需要引发系统退出()
,或者只使用sys.exit()
(其作用相同)。您需要引发错误,或者至少使用sys.exit(0)
。
工作原理如下:
import sys
if not input(': ').lower() in ['yes','y','1']:
sys.exit(0)
适用于你的例子是
simulations = input("How many times would you like to run the simulation? ")
import sys
# Invalid answer, system exit
if (not simulations) or int(simulations) <=0:
print("That is not a valid number of simulations.")
print("Shutting down.")
sys.exit(0)
simulations_num = int(simulations)
#the rest of my code comes here
simulations=input(“您希望运行模拟多少次?”)
导入系统
#回答无效,系统退出
如果(非模拟)或int(模拟)来处理代码:
首先,您需要在SystemExit前面添加“raise”关键字,以使其正常工作。
第二,要建立一种必须按Enter键才能退出程序的情况,可以使用input()
更正版本:
simulations = input("How many times would you like to run the simulation? ")
# Invalid answer, system exit
if (not simulations) or int(simulations) <= 0:
print("That is not a valid number of simulations.")
print("Shutting down.")
input("Press Enter to exit...")
raise SystemExit("Exiting... Reason: invalid input!")
simulations_num = int(simulations)
# the rest of my code comes here
simulations=input(“您希望运行模拟多少次?”)
#回答无效,系统退出
如果(不是模拟)或int(模拟),ValueError
是试图将字母/字符转换为int。SystemExit
是一个表达式,而不是对exit函数的调用。我认为出于某种原因,SystemExit可以与sys.exit()互换。谢谢你的支持help@Mr.Oddicus是的,重要的是你需要提高它,否则它就被忽略了。