Python Basics

Whitespace Is Important


In [1]:
listOfNumbers = [1, 2, 3, 4, 5, 6]

for number in listOfNumbers:
    print number,
    if (number % 2 == 0):
        print "is even"
    else:
        print "is odd"
        
print "All done."


1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
All done.

Importing Modules


In [2]:
import numpy as np

A = np.random.normal(25.0, 5.0, 10)
print A


[ 18.9123893   24.82816779  29.44800245  27.80224122  28.49027554
  27.91360598  22.51271343  21.21800932  28.72865468  29.01646768]

Lists


In [3]:
x = [1, 2, 3, 4, 5, 6]
print len(x)


6

In [4]:
x[:3]


Out[4]:
[1, 2, 3]

In [5]:
x[3:]


Out[5]:
[4, 5, 6]

In [6]:
x[-2:]


Out[6]:
[5, 6]

In [7]:
x.extend([7,8])
x


Out[7]:
[1, 2, 3, 4, 5, 6, 7, 8]

In [8]:
x.append(9)
x


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

In [9]:
y = [10, 11, 12]
listOfLists = [x, y]
listOfLists


Out[9]:
[[1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12]]

In [10]:
y[1]


Out[10]:
11

In [11]:
z = [3, 2, 1]
z.sort()
z


Out[11]:
[1, 2, 3]

In [12]:
z.sort(reverse=True)
z


Out[12]:
[3, 2, 1]

Tuples


In [13]:
#Tuples are just immutable lists. Use () instead of []
x = (1, 2, 3)
len(x)


Out[13]:
3

In [14]:
y = (4, 5, 6)
y[2]


Out[14]:
6

In [15]:
listOfTuples = [x, y]
listOfTuples


Out[15]:
[(1, 2, 3), (4, 5, 6)]

In [16]:
(age, income) = "32,120000".split(',')
print age
print income


32
120000

Dictionaries


In [17]:
# Like a map or hash table in other languages
captains = {}
captains["Enterprise"] = "Kirk"
captains["Enterprise D"] = "Picard"
captains["Deep Space Nine"] = "Sisko"
captains["Voyager"] = "Janeway"

print captains["Voyager"]


Janeway

In [18]:
print captains.get("Enterprise")


Kirk

In [19]:
print captains.get("NX-01")


None

In [20]:
for ship in captains:
    print ship + ": " + captains[ship]


Voyager: Janeway
Deep Space Nine: Sisko
Enterprise D: Picard
Enterprise: Kirk

Functions


In [21]:
def SquareIt(x):
    return x * x

print SquareIt(2)


4

In [22]:
#You can pass functions around as parameters
def DoSomething(f, x):
    return f(x)

print DoSomething(SquareIt, 3)


9

In [23]:
#Lambda functions let you inline simple functions
print DoSomething(lambda x: x * x * x, 3)


27

Boolean Expressions


In [24]:
print 1 == 3


False

In [25]:
print (True or False)


True

In [26]:
print 1 is 3


False

In [27]:
if 1 is 3:
    print "How did that happen?"
elif 1 > 3:
    print "Yikes"
else:
    print "All is well with the world"


All is well with the world

Looping


In [28]:
for x in range(10):
    print x,


0 1 2 3 4 5 6 7 8 9

In [29]:
for x in range(10):
    if (x is 1):
        continue
    if (x > 5):
        break
    print x,


0 2 3 4 5

In [30]:
x = 0
while (x < 10):
    print x,
    x += 1


0 1 2 3 4 5 6 7 8 9

Activity

Write some code that creates a list of integers, loops through each element of the list, and only prints out even numbers!


In [ ]: