[Tutor] How to exit program without sys.exit()

wesley chun wescpy at gmail.com
Thu Dec 18 01:54:53 CET 2008


> I make these silly programs to learn from examples I find on the list. I put
> a couple together just to practice. I have heard it is not a good idea to
> use sys.exit() but I can not figure out how to do it. Also any and all
> comments are welcome. Thanks


david,

welcome to Python!  it's definitely a good thing to read this list and
even more importantly, to practice. as far as your inquiry goes, you
don't need *any* sys.exit() calls in your code. just remove them plus
the else statement above each, as in:

> #!/usr/bin/python
> import sys
> _count = 0
>
> def getinfo():
>    answer = yesno("Enter y to continue, n to exit: y/n >> ")
>    if answer == "y":
>        getnumber()
>
> def counter():
>    global _count
>    _count += 1
>    return _count
>
> def yesno(question):
>    responce = None
>    while responce not in ("y", "n"):
>        responce = raw_input(question).lower()
>    return responce
>
> def getnumber():
>    try:
>        num = int(raw_input("Enter a number between 25 and 75: "))
>        if 25 < num < 75:
>            print "WOW you are smart ", sayit()
>    except ValueError:
>        print "Please Enter a number!", getnumber()
>
>
> def sayit():
>    print "Your total correct answers is", counter()
>    again()
>
>
> def again():
>    onemore = raw_input("Again? y/n >> " )
>    if onemore.lower() == "y":
>        getnumber()
>    elif onemore.lower() == "n":
>        getinfo()
>
> def main():
>    getinfo()
>
> if __name__=="__main__":
>    main()

it should still work the same as before.  your functions will return
to the caller, and they will exit in the same way. finally, when
main() is done, your app is automatically exits.

one other suggestion... you have a lot of functions. it's possible to
reduce the total number, esp. since they're pretty much all one-offs.
generally, you want to employ functions for code that is used more
than once during a single execution of your code.  with your app, you
can probably get away with not having any functions at all.

cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list