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.
1 2 3 4 5 6 7 8
import sys listofitems =  # Code here that does something with listofitems if len(listofitems) < 2: sys.exit('listofitems not long enough')