Intro to Python

The plan

Let’s do something fun!

How about parsing some stats? See for Team stats for AL Teams for years 2001-2006

Can we write enough Python to answer some questions about the data?


Running a command line program

Downloading a file from the internet

Exercise 1

Write a program that downloads a url and prints its contents.

Sample run

$ python
... lots of output ....

Sample code for accessing the command line:

import sys

url = sys.argv[-1]
print url

Basic types

Exercise 2

Read a file url from the command line and:

  1. break your file contents apart into a list of strings

  2. print the number of lines in the list

  3. print the list

More about Types

Let’s explore list and str a little more thoroughly

More about Lists

Everything about lists: indexes and slices, methods, and mutability.


A lot like lists (indexing/slicing, looping)

But different too. split/join and "stringy" methods.


Exercise 3

Make a list of just the home runs hit. Print it out.

Extra credit: print the total number of homeruns. See sum - but watch out for strings! Sample output:

$ python
xxxx (Total)

The dict Type

Exercise 4

Make a dictionary with team’s home run totals. Print it out.

BONUS: print out the team with the highest home run total.

$ python
{'DET': 988, 'NYY': 1337,
 ... snip ...}