Some things about Python

This document will give you a brief introduction to some concepts that you will find useful

To run each cell, press Shift + Enter

Arithmetics

For example, let's add 3 plus 5


In [4]:
3.0 + 5.0


Out[4]:
8.0

In [5]:
#multiplication
3.0 * 5.0


Out[5]:
15.0

In [6]:
#exponents with **
2.0**3


Out[6]:
8.0

Note that the pound symbol #, is used to write a comment

The rules of arithmetic are obeyed in python


In [7]:
(15.0 + 3.5) / 0.5 - 0.5**2


Out[7]:
36.75

We can assign values to variables


In [9]:
x = 9.0
x


Out[9]:
9.0

In [11]:
# y is x times 5.0, if x is 9 then y = 45
y = x * 5.0

#Then 45 plus 9
y + x


Out[11]:
54.0

Conditions

We would sometimes want to perform an action after a condition. For that we use the if statement. For example to know if someone is under 21 years old:


In [4]:
age = 17

# here we are using < , but you can also use, <=, >, == for equal and != for different   
if age < 21 :
    print "under 21"
else:
    print "21 or older"


under 21

Repetitions (Loops)

To do several times the same action, as long as a condition is true. We can use the while comand


In [18]:
i = 1

while i < 10 :
    print i
    i = i + 1


1
2
3
4
5
6
7
8
9

Doing plots, libraries and functions

First we want to tell the program to use some capabilities that we did not right and are not included by default


In [1]:
%matplotlib inline 
#importing libraries to use 
import numpy as np
import matplotlib.pyplot as plt

In [2]:
#function that gives us the cosine of a number
def f(x):
    return np.cos(x)

print f(np.pi)
print f(0)


-1.0
1.0

In [3]:
#create an array of numbers from 0 to 5 with 0.1 increments
t = np.arange(0.0, 5.0, 0.1)
t


Out[3]:
array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9,  1. ,
        1.1,  1.2,  1.3,  1.4,  1.5,  1.6,  1.7,  1.8,  1.9,  2. ,  2.1,
        2.2,  2.3,  2.4,  2.5,  2.6,  2.7,  2.8,  2.9,  3. ,  3.1,  3.2,
        3.3,  3.4,  3.5,  3.6,  3.7,  3.8,  3.9,  4. ,  4.1,  4.2,  4.3,
        4.4,  4.5,  4.6,  4.7,  4.8,  4.9])

In [4]:
#evaluate function for values of t 
f(t)


Out[4]:
array([ 1.        ,  0.99500417,  0.98006658,  0.95533649,  0.92106099,
        0.87758256,  0.82533561,  0.76484219,  0.69670671,  0.62160997,
        0.54030231,  0.45359612,  0.36235775,  0.26749883,  0.16996714,
        0.0707372 , -0.02919952, -0.12884449, -0.22720209, -0.32328957,
       -0.41614684, -0.5048461 , -0.58850112, -0.66627602, -0.73739372,
       -0.80114362, -0.85688875, -0.90407214, -0.94222234, -0.97095817,
       -0.9899925 , -0.99913515, -0.99829478, -0.98747977, -0.96679819,
       -0.93645669, -0.89675842, -0.84810003, -0.79096771, -0.7259323 ,
       -0.65364362, -0.57482395, -0.49026082, -0.40079917, -0.30733287,
       -0.2107958 , -0.11215253, -0.01238866,  0.08749898,  0.18651237])

In [5]:
#plot cosine 
plt.plot(t, f(t))
plt.show()



In [ ]: