Quantcast
Channel: #! code - Python
Viewing all articles
Browse latest Browse all 4

Stopping Code Execution In Python

$
0
0

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
2
importsyssys.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
2
3
4
5
6
7
8
importsys 
listofitems =[] 
# Code here that does something with listofitems 
iflen(listofitems)<2:
  sys.exit('listofitems not long enough')
Category: 
Tags: 

Viewing all articles
Browse latest Browse all 4

Trending Articles