0

This is my code:

sleep = input("Commander, would you like to sleep now? If yes then we can take out your bed. ")
if sleep == "yes":
    Energy = Energy + 5
    print("We have taken out your bed. The spaceship is on autopilot and you may now sleep.")
    time.sleep(4)
    print("2 weeks later...")
else:
    Energy = Energy - 5
    print("Ok. It is all your choice. BUT you WILL lose energy. Lets carry on with the journey. You have",Energy,"energy remaining.")
    time.sleep(4)
print("Commander, you have been extremely successful so far. Well done and keep it up!")
time.sleep(6)
direction = input("Oh no Sir! There is trouble ahead! Please make your decision quick. It's a matter of life and death. It is also a matter of chance! There are many asteroids ahead. You may either go forwards, backwards, left or right. Make your decision...before it's too late! ")  
if direction == "left":
    Coins = Coins + 15
    Fuel =  Fuel - 15
    while True:
        print ("You have managed to pass the asteroids, you may now carry on. You have",Fuel,"fuel left.")
        break
        continue
elif direction == "backwards":
    print("You have retreated and gone back to Earth. You will have to start your mission all over again.")
    time.sleep(2.5)
    print("The game will now restart.")
    time.sleep(2)
    print("Please wait...\n"*3)
    time.sleep(5)
    keep_playing = True
    while True:
         script()
elif direction == "forwards":
    Fails = Fails + 1
    print("You have crashed and passed away. Your bravery will always be remembered even if you did fail terribly. You have failed",Fails,"times.")
    time.sleep(3)
    ans = input("Do you want to play again? ")
    if ans == "yes":
        time.sleep(3)
        script()
    else:
        print("Our Earth is now an alien world...") 
        # Program stop here...

On the last line I want the program to stop: print("Our Earth is now an alien world...")

However, I know that there are ways to stop like quit(),exit(), sys.exit(), os._exit(). The problem is that sys.exit() stops the code but with the following exception message:

Traceback (most recent call last):
  File "C:\Users\MEERJULHASH\Documents\lazy", line 5, in <module>
    sys.exit()
SystemExit

On the other hand when I try to use the os._exit() on that last line line of code an error message comes up stating that TypeError: _exit() takes exactly 1 argument (0 given). exit() and quit() are not recommended for production code.

My question: are there any exiting commands that stop your code from carrying on without showing any message or ending with >>> or that it just closes the program?

6
  • 4
    Python will automatically stop when it reaches the end of your script. Commented Jan 19, 2016 at 17:49
  • 1
    I do not mean the end of my script. I mean how to stop mid way. My python code will carry on if the user inputs right answer but if it is wrong the python code should stop. The code I have given is not my full script... Commented Jan 19, 2016 at 17:52
  • If that is the complete program, your program will end on its own after the last line is executed :) Otherwise, try to pass exit code to your sys.exit() code like sys.exit(0). It doesn't cause a traceback for me, but I am on a Mac, so it might be Windows specific. Commented Jan 19, 2016 at 17:53
  • Yes that's not my full code but i do get a traceback message when typing sys.exit() so ill try your way thnx ;) Commented Jan 19, 2016 at 17:54
  • no. This is what comes up when i type sys.exit(0) - btw i have imported sys. Commented Jan 19, 2016 at 17:56

3 Answers 3

4

You don't need a specific command. Just let your program reach its end and it will quit by itself. If you want to stop your program prematurely you can use sys.exit(0) (make sure you import sys) or os._exit(0) (import os) which avoids all of the Python shutdown logic.

You can also try a slightly safer way imo. The way I'm talking about is wrapping your main code in a try/except block, catch SystemExit, and call os._exit there, and only there!
This way you may call sys.exit normally anywhere in the code, let it "bubble-up" to the top level, gracefully closing all files and running all cleanups, and then finally calling os._exit. This is an example of what I'm talking about:

import sys
import os

emergency_code = 777

try:
    # code
    if something:
        sys.exit() # normal exit with traceback
    # more code
    if something_critical: 
        sys.exit(emergency_code)  # use only for emergencies
    # more code
except SystemExit as e:
    if e.code != emergency_code:
        raise  # normal exit
    else:
        os._exit(emergency_code)  # you won't get an exception here!
Sign up to request clarification or add additional context in comments.

3 Comments

if i import sys and try the sys.exit the message occurs which i have already stated in my question. Same for the os. Another message occurs for the os which i have also stated in my question...
everyone is misunderstanding. Please read the whole question including title. Thnx :)
@wacraby I have edited my answer. Hopefully this works for you and solves the problem you are having :)
2

The simple way to do this is:

  1. Wrap all of your code in a function, which is typically called main

    def main():
        sleep = input("Commander, would you like to sleep now? If yes then we can take out your bed. ")
        [more code snipped]
        if someConditionThatShouldMakeTheScriptEnd:
            return
        [more code if the player keeps going]
    
  2. At the bottom of your script, do

    if __name__ == '__main__':
        main()
        [optionally print an exit message]
    
  3. Anywhere you want to exit cleanly, just return out of your main function

3 Comments

can you show me exactly what you mean by putting it into the code.
Apparently not right now as the formatting fairy and I aren't getting along
for some reason when i try it the code still continues :(
1

As @MorganThrapp stated, the program will automatically exit cleanly when it finishes running.

The reason exit() and quit() are not recommended for production code are because it terminates your program outright. A better practice is to place your code in a try-except block (https://wiki.python.org/moin/HandlingExceptions). If the condition is met in the except block, the program will end cleanly and, if programmed to, spit out the exception/error raised. That is the "better" way. For all intents are purposes, quit() should work just fine.

8 Comments

The code provided is not the end of my code. I want to stop it midway. However I have tried quit() but it gives an option for the user to exit. However are there any commands that automatically exit the code without asking or that cleanly finishes the code?
That would be sys.exit(0). What behavior are you experiencing when you use that function? Make sure "import sys" is at the top of your script, and place sys.exit(0) is your else block. Let me know what it says/asks if that does not suit your needs.
this is the respone im getting when i type in sys.exit(0) and import sys at the top : Traceback (most recent call last): File "C:\Users\MEERJULHASH\Documents\PYTHON GAME!!!", line 466, in <module> script() File "C:\Users\MEERJULHASH\Documents\PYTHON GAME!!!", line 145, in script sys.exit(0) SystemExit: 0
what i want is no traceback messages or choices to exit or not
Ah, try running your script outside of IDLE ie. from command prompt. That's IDLE doing that, not your Python script. I don't know that there's a way to kill or prevent the traceback.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.