RemQ1 What is the value of 17 % 4? a. 0 b. 1 c. 3 d. 4 ------ a: RemQ2 b: PrecQ1 c: RemQ2 d: RemQ2
Fred Agbo
April 29, 2024
employee = ("Bob Cratchit", "clerk", 15)
+
Tuble)You can select or slice elements from a tuple just like you can with lists
If using tuples, you can make programs more readable by using a destructuring assignment, which breaks a tuple into named components:
employee = ("Bob Cratchit", "clerk", 15)
name, title, salary = employee
One of the most simple examples of tuple usage would be storing location information in 2d space
By storing both \(x\) and \(y\) coordinates in a tuple, it makes that information easier to store and pass around your program
When you need to use the points, best to destructure:
x,y = pt
return x, y
is the same as
return (x,y)
enumerate
zip
We have multiple ways to iterate through a string or list:
By element:
for ch in string:
# body of loop using ch
By index:
for i in range(len(string)):
# body of loop using i
Using enumerate
lets us get both!
for i, ch in enumerate(string):
# body of loop using both ch and i
Sometimes you have multiple lists that you want to loop over in a “synced” fashion
The zip
function iterates through
tuples of pairs of elements
For example
zip([1,2,3], ["one", "two", "three"])
would yield (1, "one")
, then
(2, "two")
, and then
(3, "three")
Can unpack or destructure as part of a
for
loop:
for x,y in zip([1,2,3],[4,5,6]):
# body of loop using paired x and y
When we introduced PGL early in the semester, we stressed the difference between types/classes and objects
PGL defines the GRect
class.
GRect
classClass definitions in Python start with a header line consisting
of the keyword class
and then the class
name
The body of the class will later contain definitions, but initially can just leave blank
pass
keywordclass Employee:
"""This class is currently empty!"""
Once the class is defined, you can create an object of this class type by calling the class as if it were a function:
clerk = Employee()
You can select an attribute from an object by writing out the object name, followed by a dot and then the attribute name.
As an example
clerk.name
would select the name
attribute for the
clerk
object
Attributes are assignable, so
clerk.salary *= 2
would double the clerk’s current salary
You can create a new attribute in Python by simply assigning a name and a value, just like you’d define a new variable
Employee
class called a constructor, which is responsible for
initializing attributes to a newly created object
__init__
self
self
self
s in the class with that object’s name
self
is
doingself
is always the
first parameter to the __init__
constructor
class Employee:
def __init__(self, name, title, salary):
self.name = name
self.title = title
self.salary = salary
clerk = Employee('Bob Cratchit', 'clerk', 15)
self
when creating the object, Python
supplies this reference automaticallyMost classes define additional functions called methods to allow clients to read or update attributes or manipulate the object
Methods look like a normal function definition but will
always declare the parameter
self
at the beginning of the parameter
list
Methods are defined in the body of the class and would thus look something like:
def method_name (self, other_parameters):
...body of the method...
For example
def give_raise(self, amount):
self.salary += amount
Python sets self
to be a reference to
the receiver, which is the object to which the method is
applied
clerk = Employee('Bob', 'clerk', 15)
clerk.give_raise(15)
You retrieve the method from the class itself, and then provide self manually
clerk = Employee('Bob', 'clerk', 15)
Employee.give_raise(clerk, 15)
In the object-oriented model, the client is not supposed to muck-about with the object internals
The implementation should therefore provide methods to retrieve desired attributes (called getters) or to make changes to desired attributes (called setters)
Setting up getters and setters for the attribute
salary
might look like:
def get_salary(self):
return self.salary
def set_salary(self, new_salary):
self.salary = new_salary
Getters are far more common than setters, as you don’t always want the client to have the freedom to change attributes on a whim
Python dictionaries use squiggly brackets
{}
to enclose their contents
Can create an empty dictionary by providing no key-value pairs:
empty_dict = {}
If creating a dictionary with key-value pairs
:
,
generic_dict = {'Bob': 21, 0: False, 13: 'Thirteen'}
The fundamental operation on dictionaries is selection, which is
still indicated with square brackets:
[]
Dictionaries though are unordered, so it is not
a numeric index that goes inside the
[ ]
You instead use the key directly to select corresponding values:
>>> A = {'Jack': 12, 'Jill': 17}['Jack']
>>> print(A)
12
>>> B = {True: 13, 0: 'Why?'}[0]
>>> print(B)
Why?
If you attempt to index out a key that doesn’t exist:
A = {'Jack': 12, 'Jill': 13}
print(A['Jil'])
you will get an error!
If in doubt, check for the presence of a key with the
in
operator:
if 'Jil' in A:
print(A['Jil'])
>>> d = {}
>>> d['A'] = 10
>>> d['B'] = 12
>>> print(d)
{'A':10, 'B':12}
>>> d['A'] = d['B']
>>> print(d)
{'A':12, 'B':12}
Frequently we might want to iterate through a dictionary, checking either its values or its keys
Python supports iteration with the
for
statement, which has the form of:
for key in dictionary:
value = dictionary[key]
code to work with that key and value
You can also use the .items
method to
grab both key and values together:
for key, value in dictionary.items():
code to work with that key and value
Method call | Description |
---|---|
len(dict) |
Returns the number of key-value pairs in the dictionary |
dict.get(key, value) |
Returns the value associated with the
key in the dictionary. If the key is not
found, returns the specified value, which is
None by default |
dict.pop(key) |
Removes the key-value pair corresponding to
key and returns the associated value. Will
raise an error if the key is not found. |
dict.clear() |
Removes all key-value pairs from the dictionary, leaving it empty. |
dict.items() |
Returns an iterable object that cycles through the successive tuples consisting of a key-value pair. |
While most commonly used to indicate mappings, dictionaries have seen increased use of late as structures to store records
Looks surprisingly close to our original template of:
boss = {
'name': 'Scrooge',
'title': 'founder',
'salary': 1000
}
Allows easy access of attributes without worrying about ordering
print(boss['name'])
json
json.load(file_handle)
json.dump(data_object, file_handle)
with open() as fhandle:
syntaxTo read a JSON file into a variable
data
:
import json
with open('file.json') as fh:
data = json.load(fh)
To write a variable with complex structure out to a JSON file:
import json
with open('file.json', 'w') as fh:
json.dump(data, fh)
[1, 2, 3,]
is perfectly
fine in Python, but illegal in JSONIdentifying name for first question Text of first question ------ responseA: name of next question responseB: name of next question responseC: name of next question responseD: name of next question ...more questions/answers...
RemQ1 What is the value of 17 % 4? a. 0 b. 1 c. 3 d. 4 ------ a: RemQ2 b: PrecQ1 c: RemQ2 d: RemQ2