Collections#
Q&A
Q: I’m still a bit confused on when to use print vs return in conditonals
A: In conditionals you can only usereturnis only used inside functions to get the output from the function.
Q: how come in the last activity you put “conditional = blank and python = blank” but in this example we don’t have to do that.
A: Because this is a function with a conditional inside of it. The other was just a conditional. Here the inputs are specified when executing the function.
Q: how do make a unit in the paramater a string?
A: When executing the function put quotes around the value for the parameter.
Q: How do you know whether to use Elif or Else or both
A:elifif you have an additional condition to test;elseif you have code you want to run if everything else is notTrue.
Q: I don’t understand calling vs defining vs executing
A: Calling and executing are the same thing. If you have already defined a function (written the instructions), you can call/execute it, which means actually running the function on specific inputs.
Q: Are we going to have questions like the temperature one on the exam?
A: Kind of. It would be a debugging question, so you wouldn’t have to write the code from scratch but rather fix/edit the code provided that isn’t working quite as intended.
Q: How do nested conditionals work?
A: The conditional on the outside is checked before the conditional inside.
Course Announcements
Due this week:
CL3 due Friday
A2 due Sunday
last question is a workspace question; put answer in cell with and do not delete
#gradeworkspace issue - ~solved at 10A on Mon 4/20 (If you see “Workbook.ipynb” -> click reset (you’ll now see A2-Ciphers.ipynb) -> Ask for Manual Grading by “reporting an issue” with the question)
Notes:
E1 start Monday
Sign up in prairietest if you haven’t already
Practice exam available this evening on PL (use this!); approximates the real exam
Format: 10MC, 12 short answer; 3 debugging/code reading
Bring questions to class on Thursday! (No VQ due Wed)
Collections#
Lists, Tuples, Dictionaries
Mutability & Indexing
chrandordMembership 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]
lst
[1, 'a', True]
# Print out the contents of a list
print(lst)
[1, 'a', True]
# Check the type of a list
type(lst)
list
# Length of a list
len(lst)
3
# Indexing
lst[2]
True
# Mutating a list
lst[2] = False
lst
[1, 'a', False]
Collections: Tuples#
Tuple Examples#
# Define a tuple
tup = (2, 'b', False)
# Index into a tuple
tup[0]
2
# Tuples are immutable - meaning after they defined, you can't change them
# This code will produce an error.
tup[2] = 1
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[9], line 3
1 # Tuples are immutable - meaning after they defined, you can't change them
2 # This code will produce an error.
----> 3 tup[2] = 1
TypeError: 'tuple' object does not support item assignment
Activity: Collections I#
Complete the question in this Google Form (https://forms.gle/iuL8tM7BrfA9FQcP9) and then click submit.
q1_lst = ['peanut', 'butter', '&', 'jelly']
q1_lst[-3:]
['butter', '&', 'jelly']
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)
2
# Dictionaries are indexed using their keys
dictionary['key_1']
'value_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
{'A1234': True, 'A5678': False, 'A9123': True}
# add a key-value pair
completed_assignment['A8675'] = False
completed_assignment
{'A1234': True, 'A5678': False, 'A9123': True, 'A8675': False}
# update value of specified key
completed_assignment['A5678'] = True
completed_assignment
{'A1234': True, 'A5678': True, 'A9123': True, 'A8675': False}
## remove key-value pair using del
del completed_assignment['A5678']
print(completed_assignment)
len(completed_assignment)
{'A1234': True, 'A9123': True, 'A8675': False}
3
Additional Approach to Assignment#
my_other_list = [1, 2, 3]
my_list = list((1, 2, 3))
my_tuple = tuple((1, 2, 3))
my_dict = dict([("name", "Shannon"), ("job", "Professor")])
# take a look
my_other_list
[1, 2, 3]
my_list
[1, 2, 3]
Activity: Collections II#
Complete the question in this Google Form (https://forms.gle/cspFaeJvLZ5HasJR8) and then click submit.
Fill in the ‘—’ in the code below to return the value stored in the second key.
# FOR TESTING CODE HERE
height_dict = {'height_1' : 60, 'height_2': 68, 'height_3' : 65, 'height_4' : 72}
height_dict['height_2']
68
Write the code that would create a dictionary car that stores values about your dream car’s make, model, and year
# FOR TESTING CODE HERE
car = {'make' : 'Hyundai',
'model' : 'Santa Fe',
'year' : 2022}
car
{'make': 'Hyundai', 'model': 'Santa Fe', 'year': 2022}
car['year']
2022
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
membership checks if the thing on the left of in is an element/item in the list/tuple
lst_again = [True, 13, None, 'apples', 'Shannon']
# Check if a particular element is present in the list
True in lst_again
True
# The `in` operator can also be combined with the `not` operator
'19' not in lst_again
True
# only checks for element, not part of an element
'Shan' in lst_again
False
Dictionaries
checks whether the thing on the left-hand side of in is a key in the dictionary
dict_again = {'Shannon': 36, 'Josh': 44}
# In a dictionary, checks if value is a key
'Shannon' in dict_again
True
# does not check for values in dictionary
36 in dict_again
False
# does not check for *parts* of a key
'Shan' in dict_again
False
Strings
checks if the thing on the left hand side of in is part of the string
string_again = 'Shannon and Josh'
# does look for characters in string
'Shan' in string_again
True
# order matters
'nahS' in string_again
False
Membership summary:
membership in strings, checks if string of characters is found somewhere in the string
membership in lists/tuples, checks if string of characters is an item/element in the list/tuple
membership in dictionaries, checks if string of characters is a key in the dictionary
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.
YOU NEED THIS INFORMATION FOR THE FINAL QUESTIONS ON A2.
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#
# get the unicode code point for the string 'a'
ord('a')
97
# get the character for the unicode code point 97
chr(97)
'a'
# works for emojis and any single character
ord('🤪')
129322
chr(129322)
'🤪'
Inverses#
ord and chr are inverses of one another.
inp = 'b'
out = chr(ord(inp))
assert inp == out
print(inp, out)
b b
Activity: membership & chr/ord#
Complete the question in this Google Form (https://forms.gle/Mqd7Cyaqc1E3Z6hN7) and then click submit.
Write a function
convert_with_offsetthat will take a single input parametercharacter(a single character in as input).
Inside the function, the code will convert the input
characterto its unicode code point and then add anoffsetvalue of 50, returning that value as the output from the function.
ord('g')
103
# ord always takes in a single character string - returns an integer
ord('G')
71
# cannot have an integer input to ord
ord(71)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[58], line 1
----> 1 ord(71)
TypeError: ord() expected string of length 1, but int found
def convert_with_offset(character):
return ord(character) + 50
def convert_with_offset(character):
output = ord(character) + 50
return output
97 + 50
147
convert_with_offset('a')
147
ex_lst = [0, 'untrue', '4', None]
ex_str = 'It is untrue to say it is week 5'
bool_1 = 'true' in ex_lst # lists - membership checks if item in list
print(bool_1)
bool_2 = 'true' in ex_str # strings - membership checks if characters in str
output = bool_1 and bool_2
print(output)
False
False
## TEST OUT YOUR CODE HERE
END OF MATERIAL COVERED ON EXAM 1