Quick Overview

  1. This assumes you know some coding
  2. There are great tutorials that are more self paced
  3. I just want you to continue to get a flavor of python

Indentation


In [2]:
#Indentation

a = [5,2,8,7]

for item in a:
    print item


5
2
8
7

In [3]:
for item in a:
    if item > 3:
        print item, 'is big'
    else:
        print item, 'is small'


5 is big
2 is small
8 is big
7 is big

In [4]:
# Comments

for item in a:
    if item > 3:
        # I think 3 is big
        print item, 'is big'
    else:
        print item, 'is small'


  File "<ipython-input-4-d9acce4396e0>", line 6
    else:
       ^
IndentationError: expected an indented block

Imports


In [5]:
# imports

import os
os?

In [8]:
whereami = os.getcwd()
print whereami


/user_home/w_cindeem

In [10]:
os.listdir(whereami)


Out[10]:
['.anaconda',
 '03-Conditionals_and_Control_Flow.ipynb',
 'wakaripython',
 '.kshrc',
 'scripts',
 '2013_08_Pandas_Talk.ipynb',
 '.notebook.out.log',
 '.bashrc',
 '.ipython',
 '.gateone',
 '08-Loops.ipynb',
 '.bash_profile',
 '02-Strings.ipynb',
 'PandasPythonEssentials.ipynb',
 '.bash_logout',
 '.matplotlib',
 '01-Intro.ipynb',
 '.emacs',
 '.continuum']

Variables and Pass-by-reference gotchas


In [18]:
# Variables and gotchas

a = [1,2,3]
b = a
print 'a=', a, 'b=', b


a= [1, 2, 3] b= [1, 2, 3]

In [19]:
a.append(42)
print 'b is', b


b is [1, 2, 3, 42]

Dynamic typing and Strong References


In [23]:
myint = 3
mystr = '3'
print 'myint is of ', type(myint)
print 'mystr is of ', type(mystr)


myint is of  <type 'int'>
mystr is of  <type 'str'>

In [24]:
myint + mystr


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-4df3310450c6> in <module>()
----> 1 myint + mystr

TypeError: unsupported operand type(s) for +: 'int' and 'str'

In [25]:
myint * mystr


Out[25]:
'333'

In [26]:
print myint / 22
print myint / 22.0


0
0.136363636364

In [27]:
mystr.


  File "<ipython-input-27-3412e27a46e3>", line 1
    mystr.?
          ^
SyntaxError: invalid syntax

Binary Operators and Comparisons


In [28]:
myint > 0


Out[28]:
True

In [29]:
#remember above where we defined b = a?
a is b


Out[29]:
True

In [31]:
print a
a is [1,2,3,42]


[1, 2, 3, 42]
Out[31]:
False

In [32]:
a == [1,2,3,42]
#beware accidentally doing this
# a = [1,2,3,42]


Out[32]:
True

mutable and immutable


In [35]:
mylist = ['a','b','c']
print 'original', mylist
mylist[0] = 'hey im different'
print 'new', mylist


original ['a', 'b', 'c']
new ['hey im different', 'b', 'c']

In [37]:
# small indexing aside, python indexes from 0
print mylist[0]
print mylist[1:2] #left inclusive, right NOT inclusive


hey im different
['b']

In [38]:
print mylist[-1]


c

In [39]:
mytuple = ('a','b','c')
mytuple[0] = '32'


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-39-af539ccac9b0> in <module>()
      1 mytuple = ('a','b','c')
----> 2 mytuple[0] = '32'

TypeError: 'tuple' object does not support item assignment

Data Types

  • int
  • float
  • boolean
  • None

In [40]:
myint = 1
myfloat = 1.0
mybool = True
nothing = None

In [42]:
# datetime
from datetime import datetime, date, time

mydatetime = datetime(2013, 9, 6, 11,22)
print mydatetime.day


6

In [50]:
print mydatetime.strftime('%Y-%m-%d')
print mydatetime.strftime('%b %d, %Y')


2013-09-06
Sep 06, 2013

In [51]:
import dateutil

In [52]:
dateutil.parser.parse('May 23 2013')


Out[52]:
datetime.datetime(2013, 5, 23, 0, 0)

Control Flow

  • for
  • if, elif, else
  • while
  • pass

A container holds things (like strings, ints, floats, etc)

for thing in container:

# (I now have  thing)

do something with this thing

In [53]:
for item in [1,'b',3,'a', 42]:
    if item > 0:
        print item


1
b
3
a
42

In [60]:
for something in [1,'b',3,'a', 42]:
    if isinstance(something, str):
        print  'str', something
    elif something > 1:
        pass
    else:
        print something


1
str b
str a

In [63]:
count = 0
while count < 5:
    orig = count
    print orig
    count += 1
    print 'updated', count


0
updated 1
1
updated 2
2
updated 3
3
updated 4
4
updated 5

Exceptions


In [70]:
bucket = [1,2,3,'alligator']
for thing in bucket:
    try:
        print thing, 22 + thing
    except:
        raise ValueError('Cant add 22 to %s'%thing)


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-70-276386ea0bb8> in <module>()
      4         print thing, 22 + thing
      5     except:
----> 6         raise ValueError('Cant add 22 to %s'%thing)

ValueError: Cant add 22 to alligator
 1 23
2 24
3 25
alligator

Getting a Range of numbers

range : generated a list of values

xrange : iterator that generates list of values one-by-one

enumerate : counts your items for you


In [72]:
for anint in range(5):
    print anint


0
1
2
3
4

In [73]:
for val, thingy in enumerate(['spam', 'eggs', 'foo', 'bar']):
    print thingy, 'is', val


spam is 0
eggs is 1
foo is 2
bar is 3

In [ ]: