Previous Lecture Lecture 3 Next Lecture

Lecture 3, Thu 10/08

Python Review cont. Testing, Python Errors

Recorded Lecture: 10_8_20

Dictionaries

DICT = {<key1>:<value1>, <key2>:<value2>, ... , <keyN>:<valueN>}

D = {} # Empty dictionary. Notice the curly braces instead of []
print(D)
print(len(D))

D = {'Jane':18, 'Jen':19, 'Joe':20, 'John':21}

print(D)
print(len(D))
print("Jane's age is:", D['Jane'])

# Simple way to get key / value
for x in D:
    print(x) # Prints the key
    print(D[x]) # Prints the value

Restrictions on using Dictionaries

value = D.pop("Joe")  # returns the value associated with Joe, error if doesn’t exist
print(value)
print(D)
value = D.get("jksldf") # returns none if doesn’t exist
print(value)

D["Jem"] = 22 # Adds element to dictionary
print(D)

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

# temp_test.py

# imports the biggestInt function from temp.py
from temp 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.
# temp.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 temp_test.py:

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