10. Errors and Exception Handling Flashcards
What cause an SyntaxError?
print(‘Hello) # missing final ‘
File “”, line 1
print(‘Hello)
^
SyntaxError: EOL while scanning string literal
Note how we get a SyntaxError, with the further description that it was an EOL (End of Line Error) while scanning the string literal. This is specific enough for us to see that we forgot a single quote at the end of the line. Understanding these various error types will help you debug your code much faster.
The basic keywords for dealing with exceptions are?
try and except
The basic terminology and syntax used to handle errors in Python are the try and except statements. The code which can cause an exception to occur is put in the try block and the handling of the exception is then implemented in the except block of code. The syntax follows:
try:
You do your operations here…
…
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
…
else:
If there is no exception then execute this block.
How can you run a block of code regardless if there is an exception or not?
use the ‘finally’ keyword.
The finally: block of code will always be run regardless if there was an exception in the try code block. The syntax is:
try:
Code block here
…
Due to any exception, this code may be skipped!
finally:
This code block would always be executed.
Use ‘continue’ to loop in a while block:
def askint(): while True: try: val = int(input("Please enter an integer: ")) except: print("Looks like you did not enter an integer!") continue else: print("Yep that's an integer!") break finally: print("Finally, I executed!") print(val)
What does pylint do?
pylint tests for style as well as some very basic program logic.
What does unittest do?
unittest lets you write your own test programs. The goal is to send a specific set of data to your program, and analyze the returned results against an expected result.
What does an unittest look like?
%%writefile test_cap.py
import unittest
import cap
class TestCap(unittest.TestCase):
def test_one_word(self): text = 'python' result = cap.cap_text(text) self.assertEqual(result, 'Python')
def test_multiple_words(self): text = 'monty python' result = cap.cap_text(text) self.assertEqual(result, 'Monty Python')
if __name__ == ‘__main__’:
unittest.main()