[Week 3] Encapsulating code


Now that we’ve started to practice mastering the state of objects (keeping track of their properties), we will work on making our code more efficient.

Important Concepts

  1. Functions
    • A code block which packages the code and provides a shortcut to executing the code
    • The code below shows how to pass information in, how to get information out
    • important: remember that scope means what variables can be “seen” inside and outside the function


def hello_x(x):
    y = "hello {}".format(x)
    return y
y = hello_x("world")
  1. Dictionaries
    • A python variable type that allows you to map keys to values


bob = dict()
bob['name'] = 'bob'
bob['species'] = 'turtle'
  1. Encapsulation.
    • The packaging of code to be reused later

    • Example: if we have multiple objects, and we want to make them bounce off walls,

      then we could either write the wall bouncing code for each object, or write the code once and use a function to apply it to each object.


See the slides for more information. The basic gist: practice dictionaries and functions.