Introduction to Python

Simple Expressions / Variable Assignment

The Python interpreter, which is being used to parse and execute each of these lines, can do math like a calculator:


In [1]:
2+2


Out[1]:
4

Another several examples: I'll use the "print" statement to print out the result for each calculation (if I didn't do this, it would just output the result of the last expression):


In [2]:
print 2*3
print (4+6)*(2+9)  # should calculate to 110
print 12.0/11.0


6
110
1.09090909091

One major difference between using a calculator and doing calculations on the computer is that there are a couple of types of numbers -- integers and floating point values. You can think of integers as whole numbers and floats (as floating point values are called) as supporting a decimal or fractional part of the value. This shows up sometimes is odd behavior with division.


In [3]:
print(5/3)     # Integer division gives a 'floor' value (rounding down, basically).
print(5.0/3.0) # Dividing floats (usually) gives the expected answer.
print(5.0/3)   # The interpreter uses the more complex type to infer the type for the result.
print(5/3.0)   # The order for type "upcasting" doesn't matter


1
1.66666666667
1.66666666667
1.66666666667

Let's look at another example of float math:


In [4]:
0.1 + 0.2


Out[4]:
0.30000000000000004

Wat ?!?! There are occasionally precision issues because of the way floating point values work. It's actually an interesting abstraction (feel free to study a more detailed explanation of how IEEE Floats work). This is a good example of how abstractions can 'leak' (more on this later). A good explanation of how this affects Python is here. For our purposes, this really doesn't matter. Just a curiosity, so, moving right along...


In [5]:
a = 5

In [6]:
print a


5

This may not seem very exciting at first, but variables are an important part of programming. It's good to know that you can use them in Python.


In [7]:
y = x**2 - 3*x + 12  # just like in algebra, right?


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-7-4e9076e0f7b3> in <module>()
----> 1 y = x**2 - 3*x + 12  # just like in algebra, right?

NameError: name 'x' is not defined

I know x isn't defined. Isn't that what a variable is? Not exactly... More on this error stuff later. Try this:


In [8]:
x = 10
y = x**2 - 3*x + 12
print y


82

In [ ]:

So, the variables on the right side of the equals sign have to already be assigned a value. Otherwise, the interpreter tries to evaluate the right side and assign it to the left side.

This might not seem particularly useful until you see how to use looping. Also, math on arrays of values really shows how cool this is. Check this out...


In [9]:
import numpy as np   # the python array-math library
x = np.arange(0.0, 2*np.pi, 0.01) # make an array of numbers from 0 to 2π with a number every 0.01.
y = np.sin(x)

In [10]:
print "The length of x is: %s" % (len(x))
print "The length of y is: %s" % (len(y))
print "The first 5 values in the x array are:\n%s" % x[0:5]
print "The first 5 values in the y array are:\n%s" % y[0:5]


The length of x is: 629
The length of y is: 629
The first 5 values in the x array are:
[ 0.    0.01  0.02  0.03  0.04]
The first 5 values in the y array are:
[ 0.          0.00999983  0.01999867  0.0299955   0.03998933]

In [11]:
# this imports some plotting stuff we'll use
from bokeh.plotting import output_notebook
output_notebook()
from bokeh.plotting import figure, show


Loading BokehJS ...

In [12]:
p = figure(title="Sine Example")
p.line(x, y)
show(p)


That's cool. Now let's get back to something we tried earlier. Remember that expression y = x**2 - 3*x + 12 ? In algebra, that's actually a function. In Python (and just about every other language) we have the concept of functions as well. The keyword def is used the define a function in Python:


In [13]:
def f(x):
    return x**2 - 3*x + 12

So, now you can evaluate the function by handing it a value, or parameter (in this case, we've called it x).


In [14]:
f(3)


Out[14]:
12

So earlier, we assigned the value [0.0, 0.01, 0.02 ...] to the symbol x. (I'm starting to use the more official names for things here.) What happens if we pass that symbol into the function f?


In [15]:
print x[:5]  # just to be clear that in the scope of this notebook, the symbol x is defined


[ 0.    0.01  0.02  0.03  0.04]

In [16]:
print f(x)[:5]  # only show the first 5 entries


[ 12.      11.9701  11.9404  11.9109  11.8816]

%% boom %% Mind. Blown.

So, I'm dying to see what this looks like:


In [17]:
p2 = figure()
p2.line(x, f(x))
p2_nbh = show(p2)


This is pretty math-y, what else can functions do?

Well, they can do anything you tell them...


In [18]:
import random
def headache(name, number_of_repeats=5):
    """ a pretty useless function """
    namelist = list(name)
    for i in range(0, number_of_repeats):
        random.shuffle(namelist)
        for letter in namelist:
            print letter,

In [19]:
headache("travis", 40)


s v r i a t r i a s t v t r i v a s v a t s i r s r i a v t i s a t v r i a v t r s t s r a v i v t r s i a s i t r v a r t s v a i i s t r v a t r s i a v a s r i t v a v i s t r a v t r i s r a v t s i i r t s a v a i r v s t v s t a i r i s r t v a r t s v i a r t s a i v i a s v t r t s i r a v v a s t r i i v a t r s s r v t i a v a s t i r v t s a r i v a r i s t s a i v r t v i r t a s i s v t r a a v t s i r s i v a r t a v r i t s s t r a i v a i s t v r s t i a r v

In [ ]: