Intro to Python
Class 3

@gdiannarbor   |   #GDIA2   |   #IntroToPython

Review

  • Functions - calls, definitions, returns, arguments
  • Conditions - if, elif, else
  • Loops - while, for

What we will cover today

  • More Functions
  • Method calls
  • Lists and dictionaries
  • Python builtin functions

More with Functions

Functions can also call other functions.

You can use this to break up tasks
into small pieces that rely on others to do their work.

from math import sqrt

def absolute_difference(value_a, value_b):
    return abs(value_a - value_b)

def get_hypotenuse(a, b):
    return sqrt(a ** 2 + b ** 2)

def get_area_rectangle(width, height):
    return width * height

def print_area_and_hypotenuse(x1, y1, x2, y2):
    width = absolute_difference(x1, x2)
    height = absolute_difference(y1, y2)
    area = get_area_rectangle(width, height)
    hypotenuse = get_hypotenuse(width, height)
    print('Area of the rectangle is:')
    print(area)
    print('The diagonal of the rectangle is:')
    print(hypotenuse)
            

Remember

Functions are called by their name - my_function()

They can be passed data in the form of parameters - my_function(my_parameter)

They usually return some sort of value. This all happens explicitly.

Method Calls

Methods are also called by name but are associated with an object.
Really, they are identical to functions except that the data passed into it is passed implicitly.

For example, the integers and strings we've been using have methods attached to them.


name = 'caleb'
sentence = 'the quick brown fox did the thing with the thing'

print(name.capitalize())
print(sentence.count('the'))
            

String Indexing

Python strings include methods for accessing specific characters, or substrings.

To index from the back of the string, use negative numbers.


sentence = 'Hello World'
print(sentence[0]) # prints 'H'
print(sentence[0:5]) # prints 'Hello'
print(sentence[-5]) # prints 'W'
print(sentence[-5:]) # prints 'World'

          

String Manipulation

There are also methods available for manipulating and changing the values of a string


sentence = 'Hello World'
print(sentence.split()) # prints a list: ['Hello', 'World']

shopping_list = ['apples', 'bananas', 'grapes']
print(', '.join(shopping_list))
        

Let's Develop It

  • Write a program with a function called pigLatin that takes in a word, and prints that word in Pig Latin (that is, move the first letter to the end of the word and add "-ay"). Call the function 3 times with 3 different words.

Let's Develop It

Open a Python shell and define a string varaible

Use dir(string_variable) and the help() function
to explore the various methods

Hint: Like functions, some methods take arguments and others don't

Hint: Use help() on a method.
It will tell you the arguments to use and the expected behavior

Hint: Don't be afraid of errors.
They seem to be in a foreign language but they are there to help you.
Read them carefully.

Lists

A list is an ordered collection of elements

In Python, a list is defined using [ ] with elements separated by commas, as in the following example


words = ['list', 'of', 'strings']
            

Multi-type Lists

A list can, but doesn't have to be of all one type.
A list of one type is homogenous as opposed to a list of multiple types, which is heterogeneous.


# heterogenous list
words = [0, 'list', 'of', 3, 'strings', 'and', 'numbers']
            

List Methods

Lists have several methods, the most useful of which is append

A list can be created as an empty list and have values added to it with append


to_dos = []
to_dos.append('buy soy milk')
to_dos.append('install git')
print(to_dos)
            

Iteration

Lists and many other collections are iterable.

Once defined, we can iterate on them,
performing an action with each element


shipping_cost = 2.5
prices = [3, 4, 5.25]
costs = []

for price in prices:
    costs.append(price + shipping_cost)

for cost in costs:
    print(cost)
            

Indexing

An element can also be obtained from a list through indexing

This allows us to obtain an element without iterating through the entire collection if we just want one value.

To index on a collection, follow it immediately with [index]. (index here is a number, variable or expression)


numbers = [10, 20, 30]
print(numbers[0])
            

Indexing continued

Lists and other collections in Python are zero indexed.
This means that the number 0 refers to first element in the list.


to_dos = [
    'install git', 'read email', 'make lunch',
]
print(to_dos[0])
print(to_dos[1])

print(to_dos[-1])
            

Python can index from the end of a string by using negative numbers

An IndexError results if an index is larger than the list size

Dictionaries

A dictionary is a collection of key/value pairs, defined with {}


menu_categories = {
    'food': 'stuff you eat',
    'beverage': 'stuff you drink',
}
            

Think of words in a dictionary.
The words are keys and the definitions are values.

This dictionary would be indexed with strings such as 'food' and 'beverage' instead of integers like in a list

Indexing on Dictionaries

Dictionaries aren't just for definitions. They represent a group of mappings. A mapping might be: menu items -> costs.

We can also index on dictionaries.

The most common indexes are strings,
but they can be whatever type the keys are.


menu = {
    'tofu': 4,
}

tofu_cost = menu['tofu']
            

Indexing on a key that doesn't exist results in a KeyError

If you aren't certain a key is present, you can use the get method

Dictionary Methods

Some of the most essential methods are keys, values and items


menu = {
    'tofu': 4,
    'pizza': 8,
    'baguette': 3,
}

print(menu.keys())
print(menu.values())
print(menu.items())
print(menu.get('pizza'))
print(menu.get('water'))
print(menu.get('juice', 5))
            

get will return None if the key isn't present
or a default value if provided.

Let's Develop It- Example Code


from helpers import generate_cleaned_lines

def is_word_in_file(word, filename):
    for line in generate_cleaned_lines(filename):
        # line will be a string of each line of the file in order
        # Your code goes here.
        # Your code should do something with the word and line variables and assign the value to a variable for returning

input_word = input("Enter a word to search for:")
answer = is_word_in_file(input_word, 'pride.txt')
# Display the answer in some meaningful way
            

I have used Pride and Prejudice from Project Gutenburg with my example code.

You can click this link and copy/paste the text into a new text file
called 'pride.txt' and save it in the same folder as your code

Builtins for collections

Python provides several functions that
help us work with these collections.

len() Given a collection, return its length
range() Create a list of integers in the range provided.
sorted() Given a collection, returns a sorted copy of that collection
enumerate() Returns a list of (index, element) from the list
zip() Given one or more iterables, returns a list of tuples with an element from each iterable

Examples of using Builtins


# Using len() - Determines length
print(len([1, 2]))

# range() - Quickly creates a list of integers
print(range(5))
print(range(5, 10))
print(range(0, 10, 2))
print(range(9, -1, -1))

# sorted() - Sort a given list
grades = [93, 100, 60]
grades = sorted(grades)
print(grades)
            

Builtins Examples continued


# enumerate() - Obtain the index of the element in the loop

print('To Do:')
to_dos = ['work', 'sleep', 'work']
for index, item in enumerate(to_dos):
    print('{0}. {1}'.format(index + 1, item))

print(list(enumerate(to_dos)))

# zip()
widths = [10, 15, 20]
heights = [5, 8, 12]
for width, height in zip(widths, heights):
    print('Area is {0}'.format(width * height))
            

Prep for Flask

Flask

Questions?

Let's Develop It

Write a program that opens a text file and does some processing.

  • The program should take a word as input and determine if the word appears in the file
  • The program should use at least one function to do its work and you should be able to import this function in a Python shell and call it with a word and filename
  • Use the functions from helpers.py to help with reading in the lines and/or words of the file
  • Download a book in plain text from Project Gutenburg and put it into the same directory as your python file.

The next slide has some code and other
resources that should help you get started

Resources

  • Helper functions are in helpers.py
  • Download a book in plain text from Project Gutenburg and put it into the same directory as your python file.
  • You can use this link for Pride and Prejudice. Click this link and copy/paste the text into a new text file called 'pride.txt' and save it in the same folder as your code

from helpers import generate_cleaned_lines

def is_word_in_file(word, filename):
    for line in generate_cleaned_lines(filename):
        # line will be a string of each line of the file in order
        # Your code goes here. Do something with the word and line variables
    return result

input_word = input("Enter a word to search for:")
answer = is_word_in_file(input_word, 'pride.txt')
# Display the answer in some meaningful way
            

Homework

Expand on the searching for word in text problem.

Can you display the context (3 words before and after) of each occurance of that word?

Want help?

Intro to Python
Class 4 »

@gdiannarbor   |   #GDIA2   |   #IntroToPython