1. Recap and Review

9:30 - 10:00

2. Loops and Functions - Quick Intro

10:00 - 10:45

2.1 Break

10:45 - 11:00

3. Case Study: Reading and Writing Files

11:00 - 12:15


Recap and Review

  • The iPython Notebook
  • syntax errors
  • spaces
  • context
  • explain .get() more verusus square bracket references (.get() will not break)
  • more short examples
  • what is a float? bool, int, etc.
  • coding bat examples
  • project euler
  • syntax

The Notebook

  • Name and save your notebooks
  • Careful -- Undo is Unreliable
  • Code Cells versus Markdown Cells
  • Learn Markdown
    • http://daringfireball.net/projects/markdown/
    • Mac: I use Mou (free: http://mouapp.com) though there are many others
    • Win: Try Markdownpad (http://markdownpad.com)

Syntax issues

Spaces

  • cd.. versus cd ..
    • you need a space. cd is a "verb" that says "change directories" and .. is a specific location, i.e. "one level up from here"
    • file_names_like_this.txt
  • my_dictionary["firstname"] versus my_dictionary ["firstname"]
    • No space.

Quotation Marks

  • You can use matched pairs of double quotes (") or single quotes (') as you like
  • Be careful not to use the backtick character by accident `
  • It depends what you are trying to accomplish

Exercise: write print statements that will produce each of the following:

1: Has anyone seen Fred's Computer?
2: "These quotation marks are driving me crazy!" said Fred.

Post it to the etherpad -- you have two minutes!

In [1]:
# Solution
print("Has anyone seen Fred's Computer?")
print('"These quotation marks are driving me crazy!" said Fred.')
Has anyone seen Fred's Computer?
"These quotation marks are driving me crazy!" said Fred.

Trial, error, and good record-keeping. * stackoverflow.com * Code snippets tool * Make your own "retained wisdom" documents

Data Types: int, float, bool, str, etc.

Python is a very forgiving language. Except when it isn't.

  • In lower-level languages like C, C++, and Java, you have to declare every varable before using it, and you have to specify the type of each variabe. The variable's type is usualy fixed once declared.
  • example Java variable declaration:
    int my_height_in_inches = 73;

  • Python is much more friendly. It simply tries to guess what variable type you want from the context.

    my_height_in_inches = 73 # python will guess that you want an integer my_height_in_inches = 73.1 # python will guess you want a floating point number

Why does it matter whether a variable is an integer or a float? Aren't they both just numbers? What's the difference?

type | decimal value | binary representation -----|---------------|---------------------- int | 73 | 1001001 (7 bits) float | 73.1 | 01000000 01010010 00000110 01100110 01100110 01100110 01100110 01100110 (64 bits)

  • Online calculator: http://www.binaryconvert.com
  • Read wikipedia on floating point numbers https://en.wikipedia.org/wiki/Floating_point_number

A person can convert 73 to 73.1 by writing ".1" on the end of the number, but for the computer this is a whole different ballgame

Question: How many bits are needed to represent

  • Boolean values, True and False?
  • The integers 0, 1, 2, 3, 4, 5, 6, 7 (octal)

Python has Dynamic Types

In [2]:
x = 4/3
print("The value of x is:", x)
print("The type of x is:", type(x))
('The value of x is:', 1)
('The type of x is:', <type 'int'>)

In [3]:
x_coerced_to_float = 4/3.0
x_coerced_to_float = float(4) / 3
print("The value of x_coerced_to_float is:", x_coerced_to_float)
print("The type of x_coerced_to_float is:", type(x_coerced_to_float))
('The value of x_coerced_to_float is:', 1.3333333333333333)
('The type of x_coerced_to_float is:', <type 'float'>)

In [4]:
# Quick Exercise: what is the result of this? Why?

y = float( 4 / 3)
In [5]:
print(y)
1.0

In [5]:
 

Reserved names for values

  • True
  • False
  • None

Spelled and capitalized as indicated

In [5]:
 

Coding is a practice.

Some good places to practice:

  • codingbat python examples http://codingbat.com/python
  • Project Euler https://projecteuler.net
  • Define projects for yourself. Start small, expand outward, have fun.
In [5]:
 

Loops and Functions

Loops

Why use loops?

  • Counting
  • Doing something to every element in a list, dictionary, set, file, etc.
  • Many other applications

For Loop

In [11]:
# for loop
for i in range(10):
    print i,
0 1 2 3 4 5 6 7 8 9

While Loop

In [13]:
# while loop
i = 0
while (i < 10):
    print i,
    i = i + 1
0 1 2 3 4 5 6 7 8 9

There are other types of loops, but for and while loops can handle nearly every circumstance where you need to operate of a sequence of numbers.

Exercise

  • What advantages do you see for for loop versus while loop?
  • What problems could each cause?

2 minutes to think about it - then discuss and/or ask questions

In []:
 

Exercise:

Write a for loop that prints the even numbers up to and including 24

In []:
 

Example of using a loop to make a list of the first 20 numbers that are divisible by three

This is a common type of problem. The game plan:

  1. declare an empty list
  2. iterate over a lot of cases (integers in this example)
  3. test each case. If it meets the desired conditions, append it to the list
In []:
 
In []:
 
In [20]:
div_by_3_list = []
counter = 0
desired_quantity_of_multiples = 20
while(len(div_by_3_list) < desired_quantity_of_multiples):
    counter += 1     # this is the same as saying counter = counter + 1
    if counter % 3 == 0:
        # we have found a number divisible by three
        div_by_3_list.append(counter)
In [21]:
print div_by_3_list
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60]

In []:
 

Exercise: loop over the div_by_3_list and print only the numbers divisible by 9

One way to start this off could be:

for t in div_by_3_list:
    ...do something...

10 minutes: work as a group

In []:
 
In [23]:
for t in div_by_3_list:
    if t % 9 == 0:
        print t, " is divisible by nine."
9  is divisible by nine.
18  is divisible by nine.
27  is divisible by nine.
36  is divisible by nine.
45  is divisible by nine.
54  is divisible by nine.

In []:
 

Looping over lists

In [8]:
things_I_like = ['Sushi', 'Risotto', 'Grapefruit', 'Pez']
things_I_do_not_like = ['Marshmallow Peeps', 'Avocado', 'Tripe', 'Haggis']
In [9]:
things_on_the_menu = ['Sushi', 'Beef Wellington', 'Mascarpone', 'Tripe', 'Pez']

Exercise:

  • Loop over the items on the menu
  • Print "would you like" then the item name, and then a question mark
  • If the item is on the list of things I like, print a positive response
  • If the item is on the list of things I do not like, decline the offer
  • Otherwise say you are not sure

5 minutes, work with yor table

In [9]:
 
In [10]:
for thing in things_on_the_menu:
    print "Would you like some", thing, "?        ",
    if thing in things_I_like:
        print "Yes indeed."
    elif thing in things_I_do_not_like:
        print "No thanks."
    else:
        print "Hmm, let me think about that"
Would you like some Sushi ?         Yes indeed.
Would you like some Beef Wellington ?         Hmm, let me think about that
Would you like some Mascarpone ?         Hmm, let me think about that
Would you like some Tripe ?         No thanks.
Would you like some Pez ?         Yes indeed.

In []:
 

Looping over dictionary items

In [29]:
things_I_like = ['Sushi', 'Risotto', 'Grapefruit', 'Pez']
favorite_food_score = [8, 10, 7, 11]
In [30]:
# dict(zip(list_of_keys, list_of_values)) makes a dictionary of key:value pairs
favorites_dict = dict(zip(things_I_like, favorite_food_score))  
In [31]:
favorites_dict
Out[31]:
{'Grapefruit': 7, 'Pez': 11, 'Risotto': 10, 'Sushi': 8}
In [32]:
favorites_dict.keys()
Out[32]:
['Sushi', 'Grapefruit', 'Pez', 'Risotto']
In [33]:
favorites_dict.values()
Out[33]:
[8, 7, 11, 10]
In [34]:
for k in favorites_dict.keys():
    print "My score for", k, "is:", favorites_dict[k]
My score for Sushi is: 8
My score for Grapefruit is: 7
My score for Pez is: 11
My score for Risotto is: 10

##... about that get() method

In [35]:
what_about = "Pop-Tarts"
In [36]:
favorites_dict[what_about]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-36-feaab869ee81> in <module>()
----> 1 favorites_dict[what_about]

KeyError: 'Pop-Tarts'
In [37]:
favorites_dict.get(what_about)
  • some_dictionary[some_key] will throw a KeyError if some_key is not in that dictionary's keys
  • some_dictionary.get(some_key) will return None instead
In [40]:
# This works:
if favorites_dict.get("Tilapia") is None:
    print "Have you ever tried Tilapia?"
Have you ever tried Tilapia?

In [41]:
# This does not work:
if favorites_dict["Tilapia"] is None:
    print "Have you ever tried Tilapia?"
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-41-9da5b4dddce9> in <module>()
      1 # This does not work:
----> 2 if favorites_dict["Tilapia"] is None:
      3     print "Have you ever tried Tilapia?"

KeyError: 'Tilapia'

Functions

Math

\[ f(x) = x^2\]

\(f\) is the function name
\(x\) is the argument
\(x^2\) is the value that is returned by the function

Python Version

In [6]:
def f(x):
    """
    Calculate the square of the argument and return that value.
    """
    calculated_value = x * x
    return calculated_value
In [5]:
f(3)
Out[5]:
9
  • def statement says that you are about to define a new function
  • f is the function name
    • try to use short, descriptive names.
    • a better name would have been calc_square
  • x is the argument
    • can have more than one argument
    • arguments can be of any type
    • Don't forget the parenthesis around the arugments
    • Don't forget the colon
    • Don't forget - no space between the function name and the arguments
      • def my_function(a, b, c): # yes
      • def my_function (a, b, c): # will not work
  • """Calculate the square of the argument and return that value.""" is the docstring for the function.
    • Ideally a single sentence, longer for more complex functions
    • Start with a verb
    • Write a complete sentence that ends with a period.
  • calculated_value is a variable that exists only in the context of the function
    • The scope of calculated_value is the function, f
In []:
print(calculated_vaulue)
In []:
 
In [12]:
def my_product(x, y):
    """
    Return the product of two numbers
    """
    return x + y
In [11]:
 

Very Brief Intro to Testing

Is my_product going to work?

In [13]:
my_product(2, 2)
Out[13]:
4
In [14]:
my_product(0, 0)
Out[14]:
0
In [15]:
my_product(3, 3)
Out[15]:
6
In [17]:
assert my_product(3, 3) == 9, "Three times Three is Nine."
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-17-b3d8cad569b1> in <module>()
----> 1 assert my_product(3, 3) == 9, "Three times Three is Nine."

AssertionError: Three times Three is Nine.

assert something that is either True or False, "Message to print if False"

  • If you define a function, think of a few assert statements to test the function
  • Better yet, write the assert statements first!
    • Test-Driven Development (TDD)
    • something to look into in the future
    • python's unittest module

Exercise: Define a function called my_func that passes the following tests

assert my_func(0) == 0
assert my_func(1) == 0
assert my_func(2) == 3
assert my_func(3) == 5
assert my_func(4) == 7
In [44]:
# This solution works
def my_func(y):
    """Return 2y + 1 if y > 1, otherwise return 0."""
    ret_val = 0
    if y > 1:
        ret_val = 2 * y - 1
    return ret_val
    
In [45]:
assert my_func(0) == 0
assert my_func(1) == 0
assert my_func(2) == 3
assert my_func(3) == 5
assert my_func(4) == 7
In []: