Previous Lecture Lecture 4 Next Lecture

Lecture 4, Thu 01/16

Shallow vs. Deep Equality, Python Errors, Exception Handling, Testing

Recorded Lecture

Shallow vs. Deep Equality

s1 = Student("Jane", 1234567)
s2 = Student("Jane", 1234567)
print(s1 == s2) # False, doesn’t compare values!
# Add the __eq__ method in Student.py

# s1 == s2, self is the left operand (s1), rhs is the right operand (s2)
def __eq__(self, rhs):
	return self.perm == rhs.perm
s1 = Student("Jane", 1234567)
s2 = Student("Jane", 1234567)
print(s1 == s2) # True, compares the perm values!

Python Errors

print("Start")

PYTHON!

print( Hello )
print("Start")
print( Hello )
Traceback (most recent call last):
  File "/Users/richert/Desktop/UCSB/CS9/lecture.py", line 5, in <module>
    print( Hello )
NameError: name 'Hello' is not defined

Exceptions

print("Start")
print (1/0)
Traceback (most recent call last):
  File "/Users/richert/Desktop/UCSB/CS9/lecture.py", line 5, in <module>
    print( 1/0 )
ZeroDivisionError: division by zero
print("Start")
print (‘5’ + 5)
Traceback (most recent call last):
  File "/Users/richert/Desktop/UCSB/CS9/lecture.py", line 5, in <module>
    print( '5' + 5 )
TypeError: can only concatenate str (not "int") to str

Handling Exceptions

The general rule of exception handling is:

while True:
	try:
		x = int(input("Enter an int: ")) # input() prompts user for input
		break # breaks out of the current loop
	except Exception:
		print("Input was not a number type")
	print("Let's try again...")
print(x)
print("Resuming execution")

The flow of execution is:

Catching Multiple Exceptions

Let’s slightly modify our code so another type of exception (ZeroDivisionError) may happen (in addition to entering a non-int type):

while True:
	try:
		x = int(input("Enter an int: "))
		print(x/0)
		break
	except ZeroDivisionError:
		print("Can't divide by zero")
	except Exception:
		print("Input was not a number type")
	print("Let's try again...")
print("Resuming execution")

Example of functions raising exceptions that are caught by the caller

def divide(numerator, denominator):
	if denominator == 0:
		raise ZeroDivisionError() # Change to ValueError() and observe
	return numerator / denominator

try:
	print(divide(1,1))
	print(divide(1,0))
	print(divide(2,2)) # Notice this doesn’t get executed
except ZeroDivisionError:
	print("Error: Cannot divide by zero")

print("Resuming Execution...")

Testing

Complete Test

Test Driven Development (TDD)

  1. Write test cases that describe what the intended behavior of a unit of software should. Kinda like the requirements of your piece of software
  2. Implement the details of the functionality with the intention of passing the tests
  3. Repeat until the tests pass.

Pytest

Write a function biggestInt(a,b,c,d) that takes 4 int values and returns the largest

# testFile.py

# imports the biggestInt function from lecture.py
from lecture import biggestInt 

def test_biggestInt1():
    assert biggestInt(1,2,3,4) == 4
    assert biggestInt(1,2,4,3) == 4
    assert biggestInt(1,4,2,3) == 4

def test_biggestInt2():
    assert biggestInt(5,5,5,5) == 5
    # etc.

def test_biggestInt3():
    assert biggestInt(-5,-10,-12,-100) == -5
    assert biggestInt(-100, 1, 100, 0) == 100
    # etc.
# lecture.py

def biggestInt(a,b,c,d):
	biggest = 0
	if a >= b and a >= c and a >= d:
		return a
	if b >= a and b >= c and b >= d:
		return b
	if c >= a and c >= b and c >= d:
		return c
	else:
		return d

Command to run pytest on testFile.py: