首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Python从If/ELSE语句退出程序

使用Python从If/ELSE语句退出程序
EN

Stack Overflow用户
提问于 2015-05-02 18:46:20
回答 3查看 20.8K关注 0票数 1

我试图在不使用sys.exit()的情况下退出程序,系统会询问用户是否要继续,如果用户输入“是”,则会打印一条消息说明要继续,程序将继续运行。如果他们输入了其他任何东西,就会打印一条消息,告诉他们选择退出,然后程序就会退出。

代码语言:javascript
复制
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,应该添加什么,这将导致程序退出,以及如何在代码中编写这些内容。

EN

回答 3

Stack Overflow用户

发布于 2015-05-02 18:54:36

如果你非常想不使用sys.exit(),你可以直接使用raise SystemExit。这个异常是在显式调用sys.exit()时从技术上引发的。通过这种方式,您根本不需要使用import sys

代码语言:javascript
复制
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将为您提供其他可能的方法。

票数 0
EN

Stack Overflow用户

发布于 2015-05-03 15:54:08

试试这个:

代码语言:javascript
复制
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()

代码语言:javascript
复制
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"
票数 0
EN

Stack Overflow用户

发布于 2020-12-14 17:15:30

你可以试试这个

代码语言:javascript
复制
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()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30001342

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档