Collections#
Q&A
Q: Is there a schedule to when you post the reading quizzes and such? I like to get ahead in this class over the weekends so that I can keep up with my major classes during the week but I can’t find a rhythm for this class.
A: Each week’s reading quizzes will be posted on the Friday prior. I got a bit behind last week, but will be consistent going forward.
Q: if you do a bunch of if statements in a row, does that just mean those are separate conditionals and it will run through each one in sequential order?
A: Yes! It will then treat eachif
as a new conditional (and check each one in sequence)
Q: when to use elif and when to use else
A:elif
is for when you have another condition you want to check…and that if that condition is true, you want the code to execute.else
is a catch-all. There is NO condition that it’s checking…but if allif
/elif
s above it have NOT evaluated asTrue
, the code in theelse
will execute.
Q: when I watch the videos I understand it and also I can identify a given conditions, However when a Question the one above is given, I get so confused. IDK how to overcome this issue?
A: This is normal! The first time we’re doing a question like these in class is usually the first time we’re asking you to put all the concepts together. The videos are important for initial understanding. Class is for deepening understanding. If you’re able to do 50%-80% before we discuss together, you’re in good shape! Then, hopefully, after discussing together, you’re closer to 100% and feeling better when you go to do assignments/labs on your own. That said, breaking down the question into parts is a great way. I often demo this…how to parse the question - figure out what it means. Then, add comments into hte code. Then, try to turn it into actual code. That’s the first suggestion. The second is to ask an LLM how to break something down into simpler steps. Then, see if you can do a similar question by breaking it down on your own. Happy to keep discussing!
Q: the examples tend to assign variables before the conditionals (like Q2) - is that only for conditionals or also for functions with conditionals inside them?
A: I often do that to make sure we’re really seeing what values are being checked in the conditional…but it’s not necessary. You can directly check anything that evaluates as True or False.
Q: What is the accuracy of normal integers in Python? In the odd/even conditional, I managed to get 8.00000000000000000000000001 to be even
A: Hah great question and love this observation! So, I will never test you on this in an intro level course, but Python has limitations to the precision it uses with floating point decimals. So, it rounds numbers in memory to a fixed 64 bits, which Python rounds to 8.0. There is a decimal module that you can import to do more precise floating point math (we won’t be discussing this in this class).
Q: if there is a syntax error will the code run until it reaches that error or will it not run at all?
A: For Syntax and IndentationErrors, the code will not run at all. For other errors (i.e. NameError; ValueError), the code runs until it encounters that error.
Course Announcements
Due this week:
CL3 due Friday
A2 due Sunday
Notes:
E1 starts Monday
Sign up in prairietest if you haven’t already
Practice exam now available on PL (format NOT the same)
Will finalize/update you all on Thurs, but currently considering (not final): ~15 MC (15 min); ~7 Matching/drop-down/parsons/SA (15 min); ~3 debugging/code reading (15 min)
Bring questions to class on Thursday!
If you report a question in PL: I will respond; you will see my response directly on the question you asked about
Reminder about Tues 4-5 Extra Help Group
Remind: how to turn off Gemini in Colab
Collections#
Lists, Tuples, Dictionaries
Mutability & Indexing
chr
andord
Membership operators with collections
Note: There are chapters in the book for chr
and ord
and membership operators when working with collections. Feel free to reference/watch those! But, we do NOT have video quizzes on them, as we’re discussing them in full (what you need to know) in lecture
Collections: Lists#
Lists & Indexing#
# Define a list
lst = [1, 'a', True]
# Print out the contents of a list
print(lst)
# Check the type of a list
type(lst)
# Length of a list
len(lst)
# Indexing
lst[1]
# Mutating a list
lst[2] = False
Collections: Tuples#
Tuple Examples#
# Define a tuple
tup = (2, 'b', False)
# Index into a tuple
tup[0]
# Tuples are immutable - meaning after they defined, you can't change them
# This code will produce an error.
tup[2] = 1
Activity: Collections I#
Complete the question in this Google Form (https://forms.gle/811C8Nec4XrpAGUC6) and then click submit.
Dictionaries#
Dictionaries as Key-Value Collections#
# Create a dictionary
dictionary = {'key_1' : 'value_1', 'key_2' : 'value_2'}
# Dictionaries also have a length
# length refers to how many pairs there are
len(dictionary)
# Dictionaries are indexed using their keys
dictionary['key_1']
# dictionaries are mutable
# can add key-value pairs
# can update values for existing keys
completed_assignment = {
'A1234' : True,
'A5678' : False,
'A9123' : True
}
completed_assignment
# add a key-value pair
completed_assignment['A8675'] = False
completed_assignment
# update value of specified key
completed_assignment['A5678'] = True
completed_assignment
## remove key-value pair using del
del completed_assignment['A5678']
print(completed_assignment)
len(completed_assignment)
Activity: Collections II#
Complete the question in this Google Form (https://forms.gle/3F4wKRVeL3hX2T5n6) and then click submit.
Revisiting membership: in
operator#
in
operator asks whether an element is present inside a collection, and returns a boolean answer.
# Define a new list, dictionary, and string to work with
lst_again = [True, 13, None, 'apples', 'Shannon']
dict_again = {'Shannon': 36, 'Josh': 44}
string_again = 'Shannon and Josh'
Lists/Tuples
lst_again = [True, 13, None, 'apples', 'Shannon']
# Check if a particular element is present in the list
True in lst_again
# The `in` operator can also be combined with the `not` operator
'19' not in lst_again
# only checks for element, not part of an element
'Shan' in lst_again
Dictionaries
dict_again = {'Shannon': 36, 'Josh': 44}
# In a dictionary, checks if value is a key
'Shannon' in dict_again
# does not check for values in dictionary
36 in dict_again
# does not check for *parts* of a key
'Shan' in dict_again
Strings
string_again = 'Shannon and Josh'
# does look for characters in string
'Shan' in string_again
# order matters
'nahS' in string_again
ex_lst = [0, 'untrue', '4', None]
ex_str = 'It is untrue to say it is week 5'
bool_1 = 'true' in ex_lst
bool_2 = 'true' in ex_str
output = bool_1 and bool_2
print(output)
a) True
b) False
c) This code will fail
d) I don’t know
Unicode#
Every character has a unicode code point
- an integer that can be used to represent that character.
If a computer is using unicode, it displays a requested character by following the unicode encodings of which code point
refers to which character.
ORD & CHR#
ord
returns the unicode code point for a one-character string.
chr
returns the character encoding of a code point.
ord & chr examples#
ord('a')
chr(97)
ord('🤪')
chr(129322)
Inverses#
ord
and chr
are inverses of one another.
inp = 'b'
out = chr(ord(inp))
assert inp == out
print(inp, out)
Activity: membership & chr/ord#
Complete the question in this Google Form (https://forms.gle/NuZbzsY5ZSN5Ydso9) and then click submit.
Write a function
convert_with_offset
that will take a single input parametercharacter
(a single character in as input).
Inside the function, the code will convert the input
character
to its unicode code point and then add anoffset
value of 50, returning that value as the output from the function.
## YOUR CODE HERE
# TEST YOUR FUNCTION HERE
END OF MATERIAL COVERED ON EXAM 1