Python Basics

Whitespace Is Important


In [2]:
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 [4]:
import numpy as np

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


[ 30.82312518  31.25675426  25.7345228   27.93685856  27.10292243
  23.8276339   27.89052469  22.72908952  25.82612424  28.26734292]

Lists


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


6

In [6]:
x[:3]


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

In [7]:
x[3:]


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

In [8]:
x[-2:]


Out[8]:
[5, 6]

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


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

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


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

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


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

In [12]:
y[1]


Out[12]:
11

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


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

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


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

Tuples


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


Out[15]:
3

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


Out[16]:
6

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


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

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


32
120000

Dictionaries


In [19]:
# 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 [20]:
print(captains.get("Enterprise"))


Kirk

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


None

In [22]:
for ship in captains:
    print(ship + ": " + captains[ship])


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

Functions


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

print(SquareIt(2))


4

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

print(DoSomething(SquareIt, 3))


9

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


27

Boolean Expressions


In [26]:
print(1 == 3)


False

In [27]:
print(True or False)


True

In [28]:
print(1 is 3)


False

In [29]:
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 [2]:
for x in range(5):
    print(x)


0
1
2
3
4

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

In [3]:
x = 0
while (x < 15):
    print(x)
    x += 1


0
1
2
3
4
5
6
7
8
9
10
11
12
13
14

Activity

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


In [ ]: