CSE 163
Section AX
TA 1 & TA 2
Question of the Day: What class are you most excited to take next quarter?
Or,
If you could add one class to your major that doesn’t exist, what would it be?
Important Dates and Reminders
Reminders
Office Hours?
Game Plan
What we’ve Learned so far:
What we’ll cover today:
4
Type Annotations
Type Annotations
def div(a: int, b: int | None) -> float:
if b is None:
return a / 2
else:
return a / b
def new_func(names: list[str]) –> None:
# This function’s parameter can take
# only strings in its list and returns
# None
first: str = names[0]
We can have inline type annotations!
String Formatting
(a.k.a. f strings)
String formatting
a = 3
b = 4
c = 5
f"{a}**2 + {b}**2 = {c}**2 = {c**2}"
“3**2 + 4**2 = 5**2 = 25”
animal_info = {"tom" : "cat", "jerry" : "mouse"}
f"tom is a { animal_info['tom'] }"
"tom is a cat"
Note the difference in which quote we use!
Classes Review
Defining a Class
class Student:
def __init__(self, number, name):
self._number = number
def __repr__(self):
...
def get_courses(self):
...
Classes vs. Objects
class Student:
def __init__(self, number, name):
...
def __repr__(self):
...
def get_courses(self):
...
new_student = Student(number, name)
Private vs. Public fields
class Student:
def __init__(self, number, name):
self.name = name
self._number = number
student1 = Student(123, “Adrian Salguero”)
student1.name # “Adrian Salguero”
Dunder methods
Essentially, they are built-in functions that Python lets us write with convenient syntax
class Student:
def __init__(self, number, name):
self.name = name
self._number = number
def __str__(self):
return
f"Student({self.number},
'{self.filename}')"
student1 = Student(123, “Adrian Salguero”)
print(student1)
# Student(123, “Adrian Salguero”)
# Without __str__:
# <__main__.Student object at 0x105348290>
Practice Problems!
Section code:
Solutions – Course
Solutions – Type Annotations
Solutions – Major