Previous Lecture Lecture 2 Next Lecture

Lecture 2, Wed 08/09

Python Review cont., Python Errors, Exception Handling

Recorded Lecture: 8_9_23

Functions

# Function definition
def double(n):
    ''' Returns 2 times the parameter ''' # Good to comment functions!
    return 2 * n

Mutable vs. Immutable

Example

def changeListParameter(x):
    x[0] = "!"
    return x

a = ["C","S","9"]
print(changeListParameter(a))  # ['!', 'S', '9']
print(a)  # ['!', 'S', '9']

def changeStringParameter(x):
    x = x.replace("C", "!")
    return x

b = "CS9"
print(changeStringParameter(b))  # !S9
print(b)  # CS9 - b didn't change!

Control Structures

if statements

if BOOLEAN_EXPRESSION:
	STATEMENT(s)

if/else statements

if BOOLEAN_EXPRESSION:
	STATEMENT(s) #1
else:
	STATEMENT(s) #2

elif statements

x = False
if x:
    print("Shouldn't print")
elif 4 < 5:
    print("4 < 5")
else:
    print("Shouldn't print")

While Loops

while BOOLEAN_EXPRESSION:
    STATEMENT(S)
while True:
    print("Weee!!!")  # Will always execute since BOOLEAN_EXPRESSION == True

For loops

for VARIABLE in COLLECTION:
	STATEMENT(s)
for x in range(4):
	print(x, "Hello!" * x)
	print("---")

Sets

Common set operators

s2 = set([2,4,6])		
print(s2)
print(type(s2))
print(3 in s2)
print("?" in s2)
print(5 not in s2) # True
print(len(s2))

# Combine values from two sets
s3 = set([4,5,6])
combined_set = s2 | s3
print(combined_set)

# Get the common elements from two sets
intersecting_set = s2 & s3
print(intersecting_set)

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)

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: