Reputation: 11
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?
Upvotes: 0
Views: 7718
Reputation: 15310
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!
Upvotes: 4
Reputation: 6448
The simple way to do this is:
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]
At the bottom of your script, do
if __name__ == '__main__':
main()
[optionally print an exit message]
Upvotes: 2
Reputation: 190
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.
Upvotes: 1