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

时间:2015-05-02 10:46:20

标签: python-2.7 if-statement exit

我试图在不使用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"

我正在努力解决的问题是如何添加到ELSE以将某些内容返回给我的主程序,这将导致程序退出以及如何在代码中编写代码。

4 个答案:

答案 0 :(得分:0)

只是,返回一些东西,如果返回了,那么让你的main函数退出,可以通过使用return语句,或者调用sys.exit() / {{1}来结束}。

作为一个例子,我在这里返回一个字符串(根据用户的回答不同):

raise SystemExit

现在,在def keep_going(): answer = raw_input("Do you wish to continue?") if answer == "yes": print "You have chosen to continue on" return "keep going" else: print "You have chosen to quit this program" return "please exit" 中,我可以测试返回哪些字符串main

keep_going()

虽然字符串可以用于此目的,但其他值更常用于此类任务。如果def main(): while keep_going() != 'please exit': # your code here if __name__ == "__main__": main() 返回keep_going()(而不是True)或"keep going"(而非False),则"please exit"可以写成

main

这也很自然地读取("继续做你的代码")。请注意,在这种情况下,我将返回值与def main(): while keep_going(): # your code here True之间的某些内容进行比较是真正的变量 - 以及Python的分支控制结构(像Falseif)知道它们是如何工作的,即没有必要写while,事实上它被认为是非pythonic。

答案 1 :(得分:0)

如果您非常热衷于不使用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会为您提供其他可能的方法。

答案 2 :(得分:0)

试试这个:

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,程序将继续调用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"

答案 3 :(得分:0)

您可以尝试

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()