For the second lesson, we looked at:
- Dictionaries
- Dictionary literal:
{"Shreya": 55, "Nandini": 72} - Dictionary variable:
a = {"Shreya": 55, "Nandini": 72} - Dictionary read/access:
a["Shreya"] - Dictionary write/assignment:
a["Shreya"] = 22 - Dictionary has-key test:
"Shreya" in a=> (read “yields” or “outputs” or “returns”)True,"Fred" in a=>False
- Dictionary literal:
- Functions
- Defining a function:
def functionName(parameter1, p2, p3 = "default value"):- The “body” of the function needs to be indented.
- Default values can be provided when defining function parameters, but if a parameter has a default value, then all parameters after it must also have default values, so that there is an easy rule for matching arguments to a function with the right parameter/container/variable name.
- Aside: Any line following a colon (:) must be indented. When the indentation stops, this signifies the end of that “body” of code. E.g. if-then-else statements looks like this:
if a["Shreya"] > a["Fred"]:print("Give cane to Shreya")
else:print("Give cane to Fred")
- Defining a function:
- Classes
- Classes provide a nice way to organize programming code. Intuitively, they match concepts and words that we use in real life, like Person, Car, Address, Phone Number, etc.
- Classes usually define both a set of variables that each “instance” of the class will have and a set of functions that can be used to get information about or change information about an instance of that class.
- Variables: E.g. all Persons shall have a name and password, and all Cars shall have a position and a heading/direction, etc.
- Functions (called “methods”): E.g. all Persons shall have a function that combines their first name and last name using the rule lastName + “,” + firstName, and all Cars shall have a function that moves it in the direction it is facing by 10 steps.
- Classes in Python are defined as follows:
def Person:def __init__(self, firstName, lastName):self.firstName = firstNameself.lastName = lastName
def lastNameCommaFirst(self):return self.lastName + ", " + self.firstName
- This is really shorthand for:
- Define a class type called “Person”, and define a “constructor” function that does something like this function:
def Person(firstName, lastName):person = new Person()Person.__init__(person, firstName, lastName)return person
- Where
Person.__init__is the full name of the__init__function we defined. - If we create a Person and assign them to a variable called myFriend,
myFriend = Person("Bunny", "Hopscotch"), then we could get the string"Hopscotch, Bunny"from myFriend by typingmyFriend.lastNameCommaFirst().- Note that
myFriend.lastNameCommaFirst()gets converted internally toPerson.lastNameCommaFirst(myFriend), hence the “self” in the definition. People just prefer to typemyFriend.lastNameCommaFirst()overPerson.lastNameCommaFirst(myFriend).
- Note that
