Introduction to Python (A crash course)

For those of you that know python, this aims to refresh your memory. For those of you that don't know python -- but do know programming -- this class aims to give you an idea how python is similar/different with your favorite programming language.

Printing

From the interactive python environment:


In [146]:
print "Hello World"


Hello World

From a file:


In [147]:
#!/usr/bin/env python

print "Hello World!"


Hello World!

Standard I/O


In [148]:
#  Writing to standard out:

print "Python is awesome!"


Python is awesome!

In [149]:
#  Reading from standard input and output to standard output

name = raw_input("What is your name?")
print name


What is your name?evimaria
evimaria

Data types

Basic data types:

  1. Strings
  2. Integers
  3. Floats
  4. Booleans

These are all objects in Python.


In [166]:
#String
a = "apple"
type(a)
#print type(a)


Out[166]:
str

In [167]:
#Integer 
b = 3
type(b)
#print type(b)


Out[167]:
int

In [168]:
#Float  
c = 3.2
type(c)
#print type(c)


Out[168]:
float

In [169]:
#Boolean
d = True
type(d)
#print type(d)


Out[169]:
bool

Python doesn't require explicitly declared variable types like C and other languages.

Pay special attention to assigning floating point values to variables or you may get values you do not expect in your programs.


In [170]:
14/b


Out[170]:
4

In [171]:
14/c


Out[171]:
4.375

If you divide an integer by an integer, it will return an answer rounded to the nearest integer. If you want a floating point answer, one of the numbers must be a float. Simply appending a decimal point will do the trick:


In [172]:
14./b


Out[172]:
4.666666666666667

Strings

String manipulation will be very important for many of the tasks we will do. Therefore let us play around a bit with strings.


In [173]:
#Concatenating strings

a = "Hello"  # String
b = " World" # Another string
print a + b  # Concatenation


Hello World

In [197]:
# Slicing strings

a = "World"

print a[0]
print a[-1]
print "World"[0:4]
print a[::-1]


W
d
Worl
dlroW

In [202]:
# Popular string functions
a = "Hello World"
print "-".join(a)
print a.startswith("Wo")
print a.endswith("rld")
print a.replace("o","0").replace("d","[)").replace("l","1")
print a.split()
print a.split('o')


H-e-l-l-o- -W-o-r-l-d
False
True
He110 W0r1[)
['Hello', 'World']
['Hell', ' W', 'rld']

Strings are an example of an imutable data type. Once you instantiate a string you cannot change any characters in it's set.


In [175]:
string = "string"
string[-1] = "y"  #Here we attempt to assign the last character in the string to "y"


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-175-b377f6c05723> in <module>()
      1 string = "string"
----> 2 string[-1] = "y"  #Here we attempt to assign the last character in the string to "y"

TypeError: 'str' object does not support item assignment

Whitespace in Python

Python uses indents and whitespace to group statements together. To write a short loop in C, you might use:

for (i = 0, i < 5, i++){
       printf("Hi! \n");
    }

Python does not use curly braces like C, so the same program as above is written in Python as follows:


In [176]:
for i in range(5):
    print "Hi \n"


Hi 

Hi 

Hi 

Hi 

Hi 

If you have nested for-loops, there is a further indent for the inner loop.


In [177]:
for i in range(3):
    for j in range(3):
        print i, j
    
    print "This statement is within the i-loop, but not the j-loop"


0 0
0 1
0 2
This statement is within the i-loop, but not the j-loop
1 0
1 1
1 2
This statement is within the i-loop, but not the j-loop
2 0
2 1
2 2
This statement is within the i-loop, but not the j-loop

File I/O


In [163]:
# Writing to a file
with open("example.txt", "w") as f:
    f.write("Hello World! \n")
    f.write("How are you? \n")
    f.write("I'm fine.")

In [164]:
# Reading from a file
with open("example.txt", "r") as f:
    data = f.readlines()
    for line in data:
        words = line.split()
        print words


['Hello', 'World!']
['How', 'are', 'you?']
["I'm", 'fine.']

In [165]:
# Count lines and words in a file
lines = 0
words = 0
the_file = "example.txt"

with open(the_file, 'r') as f:
    for line in f:
        lines += 1
        words += len(line.split())
print "There are %i lines and %i words in the %s file." % (lines, words, the_file)


There are 3 lines and 7 words in the example.txt file.

Lists, Tuples, Sets and Dictionaries

Number and strings alone are not enough! we need data types that can hold multiple values.

Lists:

Lists are mutable or able to be altered. Lists are a collection of data and that data can be of differing types.


In [178]:
groceries = []

# Add to list
groceries.append("oranges")  
groceries.append("meat")
groceries.append("asparangus")

# Access by index
print groceries[2]
print groceries[0]

# Find number of things in list
print len(groceries)

# Sort the items in the list
groceries.sort()
print groceries

# List Comprehension
veggie = [x for x in groceries if x is not "meat"]
print veggie

# Remove from list
groceries.remove("asparangus")
print groceries

#The list is mutable
groceries[0] = 2
print groceries


asparangus
oranges
3
['asparangus', 'meat', 'oranges']
['asparangus', 'oranges']
['meat', 'oranges']
[2, 'oranges']

Tuples:

Tuples are an immutable type. Like strings, once you create them, you cannot change them. It is their immutability that allows you to use them as keys in dictionaries. However, they are similar to lists in that they are a collection of data and that data can be of differing types.


In [179]:
# Tuple grocery list

groceries = ('orange', 'meat', 'asparangus', 2.5, True)

print groceries

#print groceries[2]

#groceries[2] = 'milk'


('orange', 'meat', 'asparangus', 2.5, True)

Sets:

A set is a sequence of items that cannot contain duplicates. They handle operations like sets in mathematics.


In [180]:
numbers = range(10)
evens = [2, 4, 6, 8]

evens = set(evens)
numbers = set(numbers)

# Use difference to find the odds
odds = numbers - evens

print odds

# Note: Set also allows for use of union (|), and intersection (&)


set([0, 1, 3, 5, 7, 9])

Dictionaries:

A dictionary is a map of keys to values. Keys must be unique.


In [181]:
# A simple dictionary

simple_dic = {'cs591': 'data-mining tools'}

# Access by key
print simple_dic['cs591']


data-mining tools

In [182]:
# A longer dictionary
classes = {
    'cs591': 'data-mining tools',
    'cs565': 'data-mining algorithms'
}

# Check if item is in dictionary
print 'cs530' in classes

# Add new item
classes['cs530'] = 'algorithms'
print classes['cs530']

# Print just the keys
print classes.keys()

# Print just the values
print classes.values()

# Print the items in the dictionary
print classes.items()

# Print dictionary pairs another way
for key, value in classes.items():
    print key, value


False
algorithms
['cs530', 'cs591', 'cs565']
['algorithms', 'data-mining tools', 'data-mining algorithms']
[('cs530', 'algorithms'), ('cs591', 'data-mining tools'), ('cs565', 'data-mining algorithms')]
cs530 algorithms
cs591 data-mining tools
cs565 data-mining algorithms

In [183]:
# Complex Data structures
# Dictionaries inside a dictionary!

professors = {
    "prof1": {
        "name": "Evimaria Terzi",
        "department": "Computer Science",
        "research interests": ["algorithms", "data mining", "machine learning",]
    },
    "prof2": {
        "name": "Chris Dellarocas",
        "department": "Management",
        "interests": ["market analysis", "data mining", "computational education",],
    }
}

for prof in professors:
    print professors[prof]["name"]


Chris Dellarocas
Evimaria Terzi

Functions


In [184]:
def displayperson(name,age):
    print "My name is "+ name +" and I am "+age+" years old."
    return
    
displayperson("Bob","40")


My name is Bob and I am 40 years old.

Libraries

Python is a high-level open-source language. But the Python world is inhabited by many packages or libraries that provide useful things like array operations, plotting functions, and much more. We can (and we should) import libraries of functions to expand the capabilities of Python in our programs.


In [185]:
import random
myList = [2, 109, False, 10, "data", 482, "mining"]
random.choice(myList)


Out[185]:
10

In [186]:
from random import shuffle
x = [[i] for i in range(10)]
shuffle(x)
print x


[[2], [7], [6], [1], [3], [5], [9], [0], [4], [8]]

APIs


In [187]:
# Getting data from an API

import requests

width = '200'
height = '300'
response = requests.get('http://placekitten.com/g/' + width + '/' + height)

print response

with open('kitten.jpg', 'wb') as f:
    f.write(response.content)


<Response [200]>

In [188]:
from IPython.display import Image
Image(filename="kitten.jpg")


Out[188]:

Python is a high-level open-source language. But the Python world is inhabited by many packages or libraries that provide useful things like array operations, plotting functions, and much more. We can (and we should) import libraries of functions to expand the capabilities of Python in our programs.


In [70]:
# Code for setting the style of the notebook
from IPython.core.display import HTML
def css_styling():
    styles = open("custom.css", "r").read()
    return HTML(styles)
css_styling()


Out[70]: