我试图在不使用sys.exit()的情况下退出程序,系统会询问用户是否要继续,如果用户输入“是”,则会打印一条消息说明要继续,程序将继续运行。如果他们输入了其他任何东西,就会打印一条消息,告诉他们选择退出,然后程序就会退出。
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
else:
print "You have chosen to quit this program"
我正在苦苦思索的是,为了将一些东西返回给我的main,应该添加什么,这将导致程序退出,以及如何在代码中编写这些内容。
发布于 2015-05-02 18:54:36
如果你非常想不使用sys.exit()
,你可以直接使用raise SystemExit
。这个异常是在显式调用sys.exit()
时从技术上引发的。通过这种方式,您根本不需要使用import sys
。
def keep_going():
answer = raw_input("Do you wish to continue?")
if (answer == "yes"):
print ("You have chosen to continue on")
else:
print "You have chosen to quit this program"
raise SystemExit
此answer将为您提供其他可能的方法。
发布于 2015-05-03 15:54:08
试试这个:
def main():
while keep_going():
keep_going()
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
return True
else:
print "You have chosen to quit this program"
return False
if __name__ == "__main__":
main()
只要程序返回true,即当用户回答"yes"
时,它就会继续调用keep_going()
一个更短的解决方案是在"yes“条件之后调用keep_going()
:
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
keep_going()
else:
print "You have chosen to quit this program"
发布于 2020-12-14 17:15:30
你可以试试这个
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
else:
print "You have chosen to quit this program"
quit()
https://stackoverflow.com/questions/30001342
复制相似问题