Previous Lecture Lecture 6 Next Lecture

Lecture 6, Thu 01/25

Assert Statements, Lists, Dictionaries

Recorded Lecture: 1_25_24

assert Statements

print("Start")
assert 5 == 5
assert True
assert 6 <= 8
print("asserts pass so far!")
assert 4 == 5 # assert statement doesn't pass
print("4 == 5 doesn't pass") # doesn't print
def isEven(value):
	''' Function that returns True if value is even,
		returns False otherwise '''
	if value // 2 == 0: # Error! Should use %
		return True
	else:
		return False

print("Checking isEven functionality")
assert isEven(3) == False # passes
print("passed isEven(3)")
assert isEven(2) == True # Fails, but should pass since 2 is even
print("passed isEven(2)")
def isEven(value):
	''' Function that returns True if value is even,
		returns False otherwise '''
	if value % 2 == 0: # Correct
		return True
	else:
		return False

print("Checking isEven functionality")
assert isEven(3) == False # pass
print("passed isEven(3)")
assert isEven(2) == True # pass
print("passed isEven(2)")

Containers

Lists

evenNumbers = [2, "4", 6, "8", 6]
print(evenNumbers)
print(type(evenNumbers))
print(len(evenNumbers)) # 5
print(evenNumbers[2])  # gets t
print(evenNumbers[-1]) #gets the last element
evenNumbers[1] = "four" # replace index 1 with "four"
print(evenNumbers)

Dictionaries

{key1:value1, key2:value2, ... , keyN:valueN}
D = {} # Empty dictionary. Notice the curly braces instead of brackets ([])

# Dictionary (mapping unique PERM numbers to Grades)
D = { 1234567:'A+', 7654321:'A-', 5555555:'B+' }
print(type(D))
print(len(D)) # 3
print(D[7654321]) # returns value 'A+'
D[5555555] = 'A-' # updates KEY with new VALUE
print(D)
D[5463278] = 'A' # creates a new KEY : VALUE pair
print(D)
del D[1234567] # removes 1234567 KEY : VALUE pair
print(D)

The in Operator

evenNumbers = [2, "4", 6, "8", 6]
D = { 1234567:'A+', 7654321:'A-', 5555555:'B+' }
s = "CMPSCW8"

print("4" in evenNumbers) #True
print(4 in evenNumbers) #False
print(7654321 in D) #True
print(9999999 in D) #False
print("SCW" in s) #True
print("CS" in s) #False
print(3 in [1, 2, 3]) # True
print(5 in [1, 2, 3]) # False