Core Python Language

Mostly copied from the official python tutorial

Invoking Python

There are three main ways to use python.

  1. By running a python file, e.g. python myscript.py
  2. Through an interactive console (python interpreter or ipython shell)
  3. In an interactive iPython notebook

We will be using the iPython notebook.

Python Versions

There are two versions of the python language out there: python 2 and python 3. Python 2 is more common in the wild but is depracated. The community is moving to python 3. As new python learners, you should learn python 3. But it is important to be aware that python 2 exists. It is possible that a package you want to use is only supported in python 2. In general, it is pretty easy to switch between then.

Some of the main changes in python 3 are:

  • print is a function
  • Integer division returns a float
  • Iterators behave differently
  • Unicode is used for encoding code

Basic Variables: Numbers and String

In [2]:
# comments are anything that comes after the "#" symbol
a = 1       # assign 1 to variable a
b = "hello" # assign "hello" to variable b

The following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here:

False      class      finally    is         return
None       continue   for        lambda     try
True       def        from       nonlocal   while
and        del        global     not        with
as         elif       if         or         yield
assert     else       import     pass
break      except     in         raise

Additionally, the following a built in functions which are always available in your namespace once you open a python interpreter

abs() dict() help() min() setattr() all() dir() hex() next() slice() any()
divmod() id() object() sorted() ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str() bool() exec() isinstance() ord() sum() bytearray()
filter() issubclass() pow() super() bytes() float() iter() print() tuple()
callable() format() len() property() type() chr() frozenset() list() range()
vars() classmethod() getattr() locals() repr() zip() compile() globals() map()
reversed() __import__() complex() hasattr() max() round() delattr() hash()
memoryview() set()
In [3]:
# how to we see our variables?
print(a)
print(b)
print(a,b)
1
hello
1 hello

All variables are objects. Every object has a type (class). To find out what type your variables are

In [4]:
print(type(a))
print(type(b))


In [5]:
# as a shortcut, iPython notebooks will automatically print whatever is on the last line
type(b)
Out[5]:
str
In [6]:
# we can check for the type of an object
print(type(a) is int)
print(type(a) is str)
True
False

Different objects attributes and methods, which can be accessed via the syntax variable.method

IPython will autocomplete if you press to show you the methods available.

In [7]:
# this returns the method itself
b.capitalize
Out[7]:
In [8]:
# this calls the method
b.capitalize()
# there are lots of other methods
Out[8]:
'Hello'
In [9]:
# binary operations act differently on different types of objects
c = 'World'
print(b + c)
print(a + 2)
print(a + b)
helloWorld
3
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in ()
      3 print(b + c)
      4 print(a + 2)
----> 5 print(a + b)

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

Math

Basic arithmetic and boolean logic is part of the core python library.

In [10]:
# addition / subtraction
1+1-5
Out[10]:
-3
In [11]:
# multiplication
5 * 10
Out[11]:
50
In [12]:
# division
1/2
Out[12]:
0.5
In [13]:
# that was automatically converted to a float
type(1/2)
Out[13]:
float
In [14]:
# exponentiation
2**4
Out[14]:
16
In [15]:
# rounding
round(9/10)
Out[15]:
1
In [16]:
# built in complex number support
(1+2j) / (3-4j)
Out[16]:
(-0.2+0.4j)
In [17]:
# logic
True and True
Out[17]:
True
In [18]:
True and False
Out[18]:
False
In [19]:
True or True
Out[19]:
True
In [20]:
(not True) or (not False)
Out[20]:
True

Conditionals

The first step to programming. Plus an intro to python syntax.

In [21]:
x = 100
if x > 0:
    print('Positive Number')
elif x < 0:
    print('Negative Number')
else:
    print ('Zero!')
Positive Number
In [22]:
# indentation is MANDATORY
# blocks are closed by indentation level
if x > 0:
    print('Positive Number')
    if x >= 100:
        print('Huge number!')
Positive Number
Huge number!

More Flow Control

In [26]:
# make a loop 
count = 0
while count < 10:
    # bad way
    # count = count + 1
    # better way
    count += 1
print(count)
10
In [29]:
# use range
for i in range(5):
    print(i)
0
1
2
3
4

Important point: in python, we always count from 0!

In [30]:
# what is range?
type(range)
Out[30]:
type
In [33]:
range?
In [37]:
# iterate over a list we make up
for pet in ['dog', 'cat', 'fish']:
    print(pet, len(pet))
dog 3
cat 3
fish 4

What is the thing in brackets? A list! Lists are one of the core python data structures.

Lists

In [64]:
l = ['dog', 'cat', 'fish']
type(l)
Out[64]:
list
In [39]:
# list have lots of methods
l.sort()
l
Out[39]:
['cat', 'dog', 'fish']
In [46]:
# we can convert a range to a list
r = list(range(5))
r
Out[46]:
[0, 1, 2, 3, 4]
In [47]:
while r:
    p = r.pop()
    print('p:', p)
    print('r:', r)
p: 4
r: [0, 1, 2, 3]
p: 3
r: [0, 1, 2]
p: 2
r: [0, 1]
p: 1
r: [0]
p: 0
r: []

There are many different ways to interact with lists. Exploring them is part of the fun of python.

list.append(x) Add an item to the end of the list. Equivalent to a[len(a):] = [x].

list.extend(L) Extend the list by appending all the items in the given list. Equivalent to a[len(a):] = L.

list.insert(i, x) Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

list.remove(x) Remove the first item from the list whose value is x. It is an error if there is no such item.

list.pop([i]) Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

list.clear() Remove all items from the list. Equivalent to del a[:].

list.index(x) Return the index in the list of the first item whose value is x. It is an error if there is no such item.

list.count(x) Return the number of times x appears in the list.

list.sort() Sort the items of the list in place.

list.reverse() Reverse the elements of the list in place.

list.copy() Return a shallow copy of the list. Equivalent to a[:].

Don't assume you know how list operations work!

In [52]:
# "add" two lists
x = list(range(5))
y = list(range(10,15))
z = x + y
z
Out[52]:
[0, 1, 2, 3, 4, 10, 11, 12, 13, 14]
In [55]:
# access items from a list
print('first', z[0])
print('last', z[-1])
print('first 3', z[:3])
print('last 3', z[-3:])
print('middle, skipping every other item', z[5:10:2])
first 0
last 14
first 3 [0, 1, 2]
last 3 [12, 13, 14]
middle, skipping every other item [10, 12, 14]

MEMORIZE THIS SYNTAX! It is central to so much of python and often proves confusing for users coming from other languages.

In terms of set notation, python indexing is left inclusive, right exclusive. If you remember this, you will never go wrong.

In [60]:
# that means we get an error from the following
N = len(z)
z[N]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
 in ()
      1 # that means we get an error from the following
      2 N = len(z)
----> 3 z[N]

IndexError: list index out of range
In [63]:
# this index notation also applies to strings
name = 'Ryan Abernathey'
print(name[:4])
Ryan
In [57]:
# you can also test for the presence of items in a list
5 in z
Out[57]:
False

Lists are not meant for math! They don't have a datatype.

In [58]:
z[4] = 'fish'
z
Out[58]:
[0, 1, 2, 3, 'fish', 10, 11, 12, 13, 14]

Python is full of tricks for iterating and working with lists

In [59]:
# a cool python trick: list comprehension
squares = [n**2 for n in range(5)]
squares
Out[59]:
[0, 1, 4, 9, 16]
In [75]:
# iterate over two lists together uzing zip
for item1, item2 in zip(x,y):
    print('first:', item1, 'second:', item2)
first: 0 second: 10
first: 1 second: 11
first: 2 second: 12
first: 3 second: 13
first: 4 second: 14

Other Data Structures

We are almost there. We have the building blocks we need to do basic programming. But python has some other data structures we need to learn about.

Tuples

Tuples are similar to lists, but they are immutable—they can't be extended or modified. What is the point of this? Generally speaking: to pack together inhomogeneous data. Tuples can then be unpacked and distributed by other parts of your code.

Tuples may seem confusing at first, but with time you will come to appreciate them.

In [69]:
# tuples are created with parentheses, or just commas
a = ('Ryan', 33, True)
b = 'Takaya', 25, False
type(b)
Out[69]:
tuple
In [70]:
# can be indexed like arrays
print(a[1]) # not the first element!
33
In [71]:
# and they can be unpacked
name, age, status = a

Dictionaries

This is an extremely useful data structure. It maps keys to values.

Dictionaries are unordered!

In [76]:
# different ways to create dictionaries
d = {'name': 'Ryan', 'age': 33}
e = dict(name='Takaya', age=25)
e
Out[76]:
{'age': 25, 'name': 'Takaya'}
In [82]:
# access a value
d['name']
Out[82]:
'Ryan'

Square brackets [...] are python for "get item" in many different contexts.

In [79]:
# test for the presence of a key
print('age' in d)
print('height' in e)
True
False
In [83]:
# try to access a non-existant key
d['height']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
 in ()
      1 # try to access a non-existant key
----> 2 d['height']

KeyError: 'height'
In [84]:
# add a new key
d['height'] = (5,11) # a tuple
d
Out[84]:
{'age': 33, 'height': (5, 11), 'name': 'Ryan'}
In [86]:
# keys don't have to be strings
d[99] = 'ninety nine'
d
Out[86]:
{99: 'ninety nine', 'age': 33, 'name': 'Ryan', 'height': (5, 11)}
In [87]:
# iterate over keys
for k in d:
    print(k, d[k])
99 ninety nine
age 33
name Ryan
height (5, 11)
In [88]:
# better way
### python 2
### for key, val in d.iteritems()
for key, val in d.items():
    print(key, val)
99 ninety nine
age 33
name Ryan
height (5, 11)

Functions

Functions are a central part of advanced python programming. You should try to write and use your own functions as often as possible.

In [121]:
# define a function
def say_hello():
    """Return the word hello."""
    return 'Hello'
In [122]:
# functions are also objects
type(say_hello)
Out[122]:
function
In [124]:
# this doesnt call
say_hello?
In [119]:
# this does
say_hello()
Out[119]:
'Hello'
In [113]:
# assign the result to something
res = say_hello()
res
Out[113]:
'Hello'
In [125]:
# take some arguments
def say_hello_to(name):
    """Return a greeting to `name`"""
    return 'Hello ' + name
In [126]:
# intended usage
say_hello_to('World')
Out[126]:
'Hello World'
In [127]:
say_hello_to(10)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in ()
----> 1 say_hello_to(10)

 in say_hello_to(name)
      2 def say_hello_to(name):
      3     """Return a greeting to `name`"""
----> 4     return 'Hello ' + name

TypeError: Can't convert 'int' object to str implicitly
In [131]:
# redefine the function
def say_hello_to(name):
    """Return a greeting to `name`"""
    return 'Hello ' + str(name)
In [132]:
say_hello_to(10)
Out[132]:
'Hello 10'
In [129]:
# take an optional keyword argument
def say_hello_or_hola(name, spanish=False):
    """Say hello in multiple languages."""
    if spanish:
        greeting = 'Hola '
    else:
        greeting = 'Hello '
    return greeting + name
In [130]:
print(say_hello_or_hola('Ryan'))
print(say_hello_or_hola('Juan', spanish=True))
Hello Ryan
Hola Juan
In [136]:
# flexible number of arguments
def say_hello_to_everyone(*args):
    return ['hello ' + str(a) for a in args]
In [137]:
say_hello_to_everyone('Ryan', 'Juan', 'Takaya')
Out[137]:
['hello Ryan', 'hello Juan', 'hello Takaya']

We could spend the rest of the day talking about functions, but we have to move on.

Individual Exercises

Fibonacci Sequence

The Fibonacci sequence is the 1,1,2,3,5,8..., the sum of each number with the preceding one. Write a function to compute the Fibonacci sequence of length n. (Hint, use some list methods.)

In [142]:
def fib(n):
    l = [1,1]
    for i in range(n-2):
        l.append(l[-1] + l[-2])
    return l
In [145]:
fib(10)
Out[145]:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

Add and Multiply Lists Item by Item

Write functions to add and multiply each item in a list.

In [146]:
def add(x,y):
    return [a + b for a,b in zip(x,y)]

def multiply(x,y):
    return [a * b for a,b in zip(x,y)]
In [147]:
add(range(10), range(10))
Out[147]:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
In [148]:
multiply(range(5), [9,3,2,5,3])
Out[148]:
[0, 3, 4, 15, 12]
In [150]:
N = 100000
%timeit multiply(range(N), range(N))
100 loops, best of 3: 12.7 ms per loop
In [151]:
import numpy as np
%timeit np.arange(N) * np.arange(N)
The slowest run took 7.60 times longer than the fastest. This could mean that an intermediate result is being cached 
10000 loops, best of 3: 173 µs per loop

On to numpy