@gdiannarbor | #GDIA2 | #IntroToPython
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)
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.
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'))
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'
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))
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.
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']
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']
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)
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)
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])
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
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
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
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.
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
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 |
# 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)
# 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))
Write a program that opens a text file and does some processing.
The next slide has some code and other
resources that should help you get started
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
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?
Not on Slack? bit.ly/gdiaa-slack
@gdiannarbor | #GDIA2 | #IntroToPython