Stopping Code Execution In Python

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.

import sys 
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.

import sys

listofitems = []

# Code here that does something with listofitems

if len(listofitems) < 2:
  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

import sys the sys command doesn't come up in read
Permalink
Very useful. thx. my game works better now u can die and it will not continue with other parts of the game.
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.

from turtle import *

speed(10)

# These two variables call two turtles.
turtle_1 = Turtle()
turtle_2 = Turtle()

def callback_1(x,y):
    color("black")
    shape("turtle")
    
def callback_2(x,y):
    color("brown")
    shape("triangle")
    circle(100, steps=3)

# These two lines of code choose color of turtles.
turtle_1.color("black")
turtle_2.color("brown")

# These two lines of code choose shape of turtles.
turtle_1.shape("turtle")
turtle_2.shape("triangle")

# This function makes turtle_1 draw a square.
def draw_square_1():
    turtle_1.setheading(270)
    turtle_1.circle(100,steps=4)

# This function makes turtle_2 draw a hexagon.
def draw_hexagon_2():
    turtle_2.setheading(90)
    turtle_2.circle(150,steps=6)

# This function moves turtle_2 to a new location.
def move_turtle_2():
    turtle_2.penup()
    turtle_2.goto(-200,200)
    turtle_2.pendown()

# This function defines turtles location after reset.
def place_turtles():
    turtle_1.color("black")
    turtle_1.shape("turtle")
    turtle_1.penup()
    turtle_1.goto(0,0)
    turtle_1.pendown()
    turtle_2.color("brown")
    turtle_2.shape("triangle")
    turtle_2.penup()
    turtle_2.goto(0,0)
    turtle_2.pendown()
    
# This function resets screen.
def start_over():
    resetscreen()
    place_turtles()

def stop():
    stop()
        
listen()

# The functions below moves the turtles or draws a shape when certain keys are pressed.
onkey(draw_square_1, "s")
onkey(move_turtle_2,"m")
onkey(draw_hexagon_2, "h")
onkey(bye,"Escape")
onkey(start_over,"space")
onkey(stop,"Home")

place_turtles()

 

Permalink

Above given syntax are useful.but i have an error

import sys
 
listofitems = []
 
# Code here that does something with listofitems
 
if len(listofitems) < 2:
  sys.exit('listofitems not long enough')

 

Permalink
add the last line mainloop()
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?

Permalink

Zylina Sala

import sys

if (answer == 2):

    print("You died when the vine broke")

    sys.exit()

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.

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.

Name
Philip Norton
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?

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!

 

Permalink

Thank you!

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!")

Permalink

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

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

Permalink

Hi LingLing,

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

import sys

print("The Calculator")

while True:
    userinput = input("add, subtract, multiply or divide, close: ")

    if userinput == 'close':
        print("ByeBye, I Hope It Helped")
        sys.exit()

    a = input("Enter first number: ")
    b = input("Enter second number: ")

    if userinput == 'add':
        add = int(a) + int(b)
        print(a + " + " + b + " = ", add)
    elif userinput == 'subtract':
        sub = int(a) - int(b)
        print(a + " + " + b + " = ",sub)
    elif userinput == 'multiply':
        multi = int(a) * int(b)
        print(a + " + " + b + " = ", multi)
    elif userinput == 'divide':
        div = int(a) / int(b)
        print(a + " + " + b + " = ", div)

 

Name
Philip Norton
Permalink
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.")

print (" ")

opt1 = int(input("TICK TOCK TICK TOCK. Choose now..."))

print (" ")

if opt1 == 1:

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.")

elif opt1 == 2:

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.")

print(" ")

thisisconfusing = int(input("Please choose now. Type three or four. Three for the boat and four for the car."))

print (" ")

if thisisconfusing == 3:

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.")

elif thisisconfusing == 4:

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?")

dabigbazooka = int(input("Press 4 to go back or 5 to continue paddling."))

print (" ")

if dabigbazooka == 4:

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?")

elif dabigbazooka == 5:

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.")

t = int(input("Choose 6 to go to the fuel station and 7 to just go."))

print (" ")

if t == 6:

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.")

elif t == 7:

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.")

teddy = int(input("Choose 8 to stay and fight or choose 9 to run."))

print (" ")

if teddy == 8:

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

elif teddy == 9:

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.....

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?

Name
Philip Norton
Permalink

Any way to stop the code without completely killing CMD?

Permalink

You mean by pressing control+c?

Name
Philip Norton
Permalink

nice one, that of the adventurer!

Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
8 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.