Python 101

Class 3

Today's Agenda

  • Lists, Tuples and Dictionaries
  • Interacting with Modules and Files
  • Handling Errors
  • Object Oriented Programming

Lists

list is an ordered set of values, where each value is identified by an index

[10, 20, 30, 40]

["spam", "bungee", "swallow"]

["orange", 3, 2.5, [1,2,"dog"]]

Excercises

  • Create a function only_evens(numbers) that accepts a list as a parameter, removes all odd numbers and returns a new list with only even numbers
  • Write a loop that traverses the following list and prints the length of each item:
    • ['spam!', 'one', ['apple','orange'], [1,2,3]]

Solutions

def is_even(n):
    return n % 2 == 0


def only_evens(number_list):
    evens = []
    for number in number_list:
        if is_even(number):
            evens.append(number)
    return evens


print only_evens([1, 2, 3, 4, 5])


my_list = ['spam!', 'one', ['apple', 'orange'], [1, 2, 3]]

for item in my_list:
    print len(item)

Tuples

Dictionaries

All of the compound data types we have studied thus far (strings, lists, tuples) are sequence types.

 

Sequence types use integers as indicies to access the values they contain within them.

 

Dictionaries are a different kind of compound type, specifically it is a mapping type.

Excercise

Save a really long string to a variable.

 

Create a dictionary that contains a key for each letter in the string and references the count of how many times that letter is present.

# Example

string = "my string"

# output
{"m": 1, "y" : 1, "s" : 2, "t" : 1, "r" : 1, "n" : 1, "g" : 1}

Solution


mystring = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
occurances = {}


def is_letter(letter):
    return letter.lower() in 'abcdefghijklmnopqrstuvwxyz'


for letter in mystring:
    lowercase_letter = letter.lower()
    if is_letter(letter):
        if letter in occurances:
            occurances[lowercase_letter] += 1
        else:
            occurances[lowercase_letter] = 1

print occurances

Modules & Files

Excercies

Create two python files, my_string.py and my_calc.py

 

In the my_calc file, made an add() function that accepts to numbers and adds them together. Do the same for my_string file but make the add function add two strings together.

 

In a third file, make a small program that uses both functions. 

Solutions

# my_calc.py

def add(a, b):
    return a + b


# my_string.py

def add(str1, str2):
    return str1 + str2


# myfile.py

import my_calc
import my_string

print my_calc.add(1, 2)
print my_string.add("Hello ", "world!")

Excercies

Create a command line program that excepts an arbitrary number of words as arguments.

 

The program should sort the words alphabetically ( HINT: use list.sort() ) and then write the words to a new file, each on its own line

 

Finally, print out the contents of the file.

Solution

from sys import argv

words = argv[1:]

words.sort()

wordfile = open('words.txt', 'w')

for word in words:
    wordfile.write(word)
    wordfile.write("\n")

wordfile.close()

wordfile = open('words.txt', 'r')
print wordfile.read()

wordfile.close()

Exception Handling

An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. 

Excercises

Create a program that asks the user for his age. If the user enters something that can not be cast to a number, handle the exception and ask the user again.

 

Remember to use raw_input()

Solution



while True:
    age = raw_input("How old are you? ")
    try:
        age = int(age)
    except ValueError:
        print "You must enter a valid integer"
        continue
    print "you are {} years old".format(age)
    break

Object Oriented Programming

Assignment

Problem: You are given two files, one contains a list of 
    names (names.txt) and the other a list of phone numbers (numbers.txt). 
    Your boss needs a single CSV file that can be loaded into excel.

    Your task is to combine both txt files into one CSV file. 

    The first and last names need to be in separate columns
    and the phone number must be in the format (555)555-5555

    One row in the csv file might look like this:

    Smith,John,(555)555-5555

Made with Slides.com