Mode Analytics: Python Tutorial (2)

Lesson 2 covers methods, functions, and libraries. To follow along, the Mode Python tutorial can be accessed here. Below is a quick summary of lesson 2:

Methods: A method is an action that can be taken on an object. For instance, the method .keys() provides (action) a list of all the keys in a dictionary (object).

Functions: A function performs an action. For instance, the function type() provides us (action) with the data type. Similarly, the function print() prints (action) an object. Some functions provide different outputs depending on the data type. For instance, len() provides us with the number of items in a list type or the number of characters in a str type. Functions can take in values (parameters or arguments) and perform logic. More details on this in lesson 6.

Libraries: A library is a bundle of code that can be imported to use for certain tasks. For instance, NumPy is a library for scientific computing and includes many mathematical functions.

Below is my code for lesson 2.

Python Notebook - Python Tutorial: Lesson 2

# Methods
# Dictionary from Lesson 1
city_pop = {'Tokyo': 13350000,
    'Los Angeles': 18550000,
    'New York City': 8400000,
    'Toronto': 2809000,

type(city_pop.keys()) # tells you the keys are a list

city_pop.keys()[2] # provides the 3rd item in list of keys

city_pop.values() # provides values of dictionary

# Practice problem: get the population for Los Angeles
city_pop.values()[2] # accessing via values list
city_pop['Los Angeles'] # acessing via dictionary

# Using methods on combined objects
# Nested lists in a dictionary object from Lesson 1
regions = {
    'New York City': [
        'The Bronx',
        'Staten Island'
    'Toronto': [
        'City of Toronto',
regions['Toronto'][2] # provides the 3rd region in Toronto
regions.keys() # Keys of the dictionary
regions.values() # Values associated with the keys

# Functions
print type(regions) # print is used to print multiple output lines
print type(regions['Toronto'])
print type(regions['Toronto'][0])

# If print is not used, python will only preint the last line of code
type(regions['Toronto'][0]) # only this output is printed

# Practice problem: What type are the values of city_pop?
type(city_pop['Toronto']) # another solution

# Length 
print (regions['Toronto'][2])

# Practice problem: What is the "length" of regions? What does that mean?
# Regions is a dictionary, so the length would be the number of pairs in that dictionary

# Libraries
import numpy
pop_values = city_pop.values() # create variable for city population values
numpy.mean(pop_values) # function from numpy that provides the mean



One thought on “Mode Analytics: Python Tutorial (2)

  1. Pingback: Mode Analytics: Python Tutorial (6) | DATADOLL

Comments are closed.