Stopping Code Execution In Python

13th April 2012 - 2 minutes read time

I am currently in the process of learning Python, so I thought I would start a series of mini blog posts detailing different things that I have found useful whilst learning how to use the language.

To stop code execution in Python you first need to import the sys object. After this you can then call the exit() method to stop the program running. It is the most reliable, cross-platform way of stopping code execution. Here is a simple example.

  1. import sys
  2. sys.exit()

You can also pass a string to the exit() method to get Python to spit this out when the script stops. This is probably the preferred way of doing things as you might otherwise not realize where the script stopped. Obviously you wouldn't just stop the script running arbitrarily, but you might want to prevent it from running if certain conditions haven't been met. Here is another example that stops execution if the length of an array is less than 2.

  1. import sys
  2.  
  3. listofitems = []
  4.  
  5. # Code here that does something with listofitems
  6.  
  7. if len(listofitems) < 2:
  8. sys.exit('listofitems not long enough')

As a side note, if you are looking to simply kill a python program that has taken over your terminal then press Ctrl+C to stop execution.

Comments

Permalink
  1. import sys
  2. the sys command doesn't come up in read

Anonymous (Tue, 03/01/2016 - 08:10)

Permalink
Very useful. thx. my game works better now u can die and it will not continue with other parts of the game.

Anonymous (Mon, 03/13/2017 - 19:59)

Permalink

I am writing a drawing program for school but need to add the stop() function but can't figure out how to define and use it.

  1. from turtle import *
  2.  
  3. speed(10)
  4.  
  5. # These two variables call two turtles.
  6. turtle_1 = Turtle()
  7. turtle_2 = Turtle()
  8.  
  9. def callback_1(x,y):
  10. color("black")
  11. shape("turtle")
  12.  
  13. def callback_2(x,y):
  14. color("brown")
  15. shape("triangle")
  16. circle(100, steps=3)
  17.  
  18. # These two lines of code choose color of turtles.
  19. turtle_1.color("black")
  20. turtle_2.color("brown")
  21.  
  22. # These two lines of code choose shape of turtles.
  23. turtle_1.shape("turtle")
  24. turtle_2.shape("triangle")
  25.  
  26. # This function makes turtle_1 draw a square.
  27. def draw_square_1():
  28. turtle_1.setheading(270)
  29. turtle_1.circle(100,steps=4)
  30.  
  31. # This function makes turtle_2 draw a hexagon.
  32. def draw_hexagon_2():
  33. turtle_2.setheading(90)
  34. turtle_2.circle(150,steps=6)
  35.  
  36. # This function moves turtle_2 to a new location.
  37. def move_turtle_2():
  38. turtle_2.penup()
  39. turtle_2.goto(-200,200)
  40. turtle_2.pendown()
  41.  
  42. # This function defines turtles location after reset.
  43. def place_turtles():
  44. turtle_1.color("black")
  45. turtle_1.shape("turtle")
  46. turtle_1.penup()
  47. turtle_1.goto(0,0)
  48. turtle_1.pendown()
  49. turtle_2.color("brown")
  50. turtle_2.shape("triangle")
  51. turtle_2.penup()
  52. turtle_2.goto(0,0)
  53. turtle_2.pendown()
  54.  
  55. # This function resets screen.
  56. def start_over():
  57. resetscreen()
  58. place_turtles()
  59.  
  60. def stop():
  61. stop()
  62.  
  63. listen()
  64.  
  65. # The functions below moves the turtles or draws a shape when certain keys are pressed.
  66. onkey(draw_square_1, "s")
  67. onkey(move_turtle_2,"m")
  68. onkey(draw_hexagon_2, "h")
  69. onkey(bye,"Escape")
  70. onkey(start_over,"space")
  71. onkey(stop,"Home")
  72.  
  73. place_turtles()

 

Josiah (Fri, 10/13/2017 - 16:05)

Permalink

Above given syntax are useful.but i have an error

  1. import sys
  2.  
  3. listofitems = []
  4.  
  5. # Code here that does something with listofitems
  6.  
  7. if len(listofitems) < 2:
  8. sys.exit('listofitems not long enough')

 

priyanka (Mon, 03/19/2018 - 06:06)

Permalink
add the last line mainloop()

Ash (Mon, 04/23/2018 - 16:43)

Permalink

I am trying to make a chode your ending game but when they die it continues with the game. How do I make specific parts of my game stop when the player chooses a action and they die?

example

river = raw_input(“oh no there is a river what do we do?”)

print “you decide”

print(“1.go through the river”)

print(“1.swing on a vine over the river”)

answer = input()

if (answer==1):

       print “you safely made it across”

if (answer==2):

       print “you died when the vine broke”

 

how do I break answer 2 without stopping answer 1?

Zylina Sala (Tue, 07/17/2018 - 22:15)

Permalink

Zylina Sala

import sys

if (answer == 2):

    print("You died when the vine broke")

    sys.exit()

Ezekiel Koenig (Wed, 10/17/2018 - 19:58)

Permalink

i'm trying to get it to 'spit it out' when i say

sys.exit("[Error]THIS HAS NOT BEEN PROGRAMMED!")

but it just exits and doesn't say that...

please reply

 

P.S. Ignore the website. i didn't know what to put.

edward green (Tue, 02/19/2019 - 17:52)

Permalink

Reading the python docs, you might be intercepting the exception that sys.exit() raises, which is then suppressing the error. Maybe?

Also, you don't have to put a website in, it's purely optional.

Permalink

print ("Guess any number between 1 and 20. You have 5 lives.")
from random import *
Memory = randint(1,20)
for i in range(5):
    Guess = int(input("What is your guess?"))

    if Guess == Memory:
        print ("Correct!")
        print ("You win!")
        break
        
    else:
        print ("Not quite.")

print ("Oops! You ran out of lives!")

^This is what I'm being taught to make (a guessing game). If the player's guess was correct, it will come up with:

Correct!

You win!

Oops! You ran out of lives!

??? How to I get the game to stop before printing "Oops! You ran out of lives!"? Can anyone help?

eva (Wed, 03/20/2019 - 21:31)

Permalink

I just read about stopping a running program from within the program using: import sys; sys.exit('program stopping')

Very cool.  When I tried this in Python 3.7 without the sys. in front of the exit, I got a window pop up asking if I really wanted to 'kill' or cancel.  What's up with that?

Thanks!

 

Treehugger Dave (Thu, 10/10/2019 - 12:40)

Permalink

Thank you!

Anonymous (Tue, 05/26/2020 - 16:49)

Permalink

    else:
        print ("Not quite.")

print ("Oops! You ran out of lives!")

 

Fix it to:

    else:
        print ("Not quite.")

       print ("Oops! You ran out of lives!")

Anonymous (Wed, 06/10/2020 - 09:29)

Permalink

Hey, Im tyring to do a simailr project, but no matter what i do, nothing can stop my code. Can someone help me?

Potato_P.J. (Mon, 10/12/2020 - 20:55)

Permalink

Hi, I'm trying to make a basic calculator. I want the person to close the thing when you want but i can't make it work. I can put the code in the comment and someone maybe would like to help me. It would be super helpful if someone helped me just to turn it of. I hope somebody reads this and helps me. I am using Microsoft Visual studio 2019 and i don't know if there is another way to make the code stop there or if you can use the same code in difrent compilars.
And I hope someone can understand me cause I'm not from a english speaking contury.
Here is my code:
 

print("The Calculator")
a = input("Enter A Number:")
b = input("Enter A Number:")
add = float(a) + float(b)
sub = float(a) - float(b)
multi = float(a) * float(b)
div = float(a) / float(b)
import sys 

if input("Add, Subtract, Multiply or Divide:") == "Add":
    print(a + "+" + b + "=")
    print(add)
    if input("Close Or Continue:") == "Close":
        print("ByeBye, I Hope It Helped")
        exit()
        print("Hello")
    else:
        print("Here Comes The Next One")
if input("Add, Subtract, Multiply or Divide:") == "Subtract":
    print(a + "-" + b + "=")
    print(sub)
    if input("Close Or Continue:") == "Close":
        print("ByeBye, I Hope It Helped")
        print(exit())
    else:
        print("Here Comes The Next One")
if input("Add, Subtract, Multiply or Divide:") == "Multiply":
    print(a + "*" + b + "=")
    print(multi)
    if input("Close Or Continue:") == "Close":
        print("ByeBye, I Hope It Helped")
        print(exit())
    else:
        print("Here Comes The Next One")
if input("Add, Subtract, Multiply, Divide:") == "Divide":
    print(a + "/" + b + "=")
    print(div)
    if input("Close Or Continue:") == "Close":
        print("ByeBye, I Hope It Helped")
        print(exit())
    else:
        print("Here Comes The Next One")

LingLing (Sat, 01/30/2021 - 18:31)

Permalink

Hi LingLing,

I rewrote your calculator a little. Let me know what you think.

  1. import sys
  2.  
  3. print("The Calculator")
  4.  
  5. while True:
  6. userinput = input("add, subtract, multiply or divide, close: ")
  7.  
  8. if userinput == 'close':
  9. print("ByeBye, I Hope It Helped")
  10. sys.exit()
  11.  
  12. a = input("Enter first number: ")
  13. b = input("Enter second number: ")
  14.  
  15. if userinput == 'add':
  16. add = int(a) + int(b)
  17. print(a + " + " + b + " = ", add)
  18. elif userinput == 'subtract':
  19. sub = int(a) - int(b)
  20. print(a + " + " + b + " = ",sub)
  21. elif userinput == 'multiply':
  22. multi = int(a) * int(b)
  23. print(a + " + " + b + " = ", multi)
  24. elif userinput == 'divide':
  25. div = int(a) / int(b)
  26. print(a + " + " + b + " = ", div)

 

Permalink
  1. print ("Hello young adventurer, so you lust for battle... You are in a small hut next to the river Thames. You have just recieved a message, you must stop a group of men who plan to try and blow up the royal family at twelve hundred hours today. You have eight hours to stop them... So will you be the hero??? Or the scaredycat??? Press 1 to be the hero. Press 2 to be the scaredycat.")
  2.  
  3. print (" ")
  4.  
  5. opt1 = int(input("TICK TOCK TICK TOCK. Choose now..."))
  6.  
  7. print (" ")
  8.  
  9. if opt1 == 1:
  10.  
  11. print ("You fool, you should have stayed home, well you have chosen now. You rush outside and reach the Thames. Should you take the Thames or your car. The Thames will be quicker but it will be dangerous.")
  12.  
  13. elif opt1 == 2:
  14.  
  15. print ("A wise decision. You are too lazy to inform the authorities and have put hundreds of people inside the castle to indirect death. You are a coward and will do anything to save your own neck.")
  16.  
  17. print(" ")
  18.  
  19. thisisconfusing = int(input("Please choose now. Type three or four. Three for the boat and four for the car."))
  20.  
  21. print (" ")
  22.  
  23. if thisisconfusing == 3:
  24.  
  25. print ("You choose the boat. Suddenly, a strong current pulls on your canooe. You must choose quickly,you can continue paddleing or fall back and go into the car.")
  26.  
  27. elif thisisconfusing == 4:
  28.  
  29. print ("You choose the car. A good choise. You start it up. You look down and suddenly see the fuel monitor is low. Can you make it to the fuel station or will you have to go now?")
  30.  
  31. dabigbazooka = int(input("Press 4 to go back or 5 to continue paddling."))
  32.  
  33. print (" ")
  34.  
  35. if dabigbazooka == 4:
  36.  
  37. print ("You choose the car. A good choise. You start it up. You look down and suddenly see the fuel monitor is low. Can you make it to the fuel station or will you have to go now?")
  38.  
  39. elif dabigbazooka == 5:
  40.  
  41. print ("A sudden jolt runs through the boat. You gasp as you feel water rushing in. Your feet are numb. You manage to get onto a rock. There is nothing you can do. You have failed. GAME OVER.")
  42.  
  43. t = int(input("Choose 6 to go to the fuel station and 7 to just go."))
  44.  
  45. print (" ")
  46.  
  47. if t == 6:
  48.  
  49. print ("You rush to the nearest fuel station and get the fuel along with extra. You rush back to zoom off into the night. Suddenly, you see a hideous glint of steel as two thieves bang on your window. You hear them speaking but can't hear them. You are numb with fear.")
  50.  
  51. elif t == 7:
  52.  
  53. print ("You get into the car and zoom off. Suddenly, when you are on dfsdhgfakgdhasfd junction, the car runs out of fuel. You are in the middle of nowhere. You are doomed... GAME OVER.")
  54.  
  55. teddy = int(input("Choose 8 to stay and fight or choose 9 to run."))
  56.  
  57. print (" ")
  58.  
  59. if teddy == 8:
  60.  
  61. print ("You jump out the car towards the thieves and fight. You don't notice the knife slip into your back as darkness comes round. GAME OVER")
  62.  
  63. elif teddy == 9:
  64.  
  65. print ("Good choise. You drive off into the darkness, leaving te thieves in your dust.")

i am trying to make an adventure game but every time you die you just continue with the game. PLZ HELP. PS - sys.exit() doesn't work :(... PSSSSSS - I am using repl.it / repl.com python.... whatever dey changed it tooooo. PSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS - I am pisseddddd.... Plz help.....

mo (Thu, 03/18/2021 - 19:45)

Permalink

Hi Mo,

I think my comment form has eaten some of your code. Pop it in pastebin or something and I'll take a look :)

However, you'll probably want to look at my previous comment above that shows how to do this sort of thing using a loop. Might be worth looking into?

Permalink

Any way to stop the code without completely killing CMD?

Anonymous (Fri, 03/19/2021 - 14:22)

Permalink

nice one, that of the adventurer!

estrywetrrquewrvt (Thu, 07/15/2021 - 17:16)

Add new comment

The content of this field is kept private and will not be shown publicly.