Fundamentals of Python

This notebook contains a small review of Python basics. We will only review several core concepts in Python with which we will be working a lot. The lecture video for this notebook will discuss some of these basics in more detail. If you are already familiar with Python, you may feel free to skip this.

If you are a beginner to Python, it will be very helpful to review a more comprehensive tutorial before moving on.

Online resources for learning Python for beginners

A review of core concepts in Python follows:

Variables

You can assign any item in Python to a variable, to refer to or operate on later.


In [1]:
myVariable = 'hello world'
print(myVariable)


hello world

Lists

We start with the most basic data containers in Python, lists:


In [2]:
# basic list in Python
X = [2, 5, 7, -2, 0, 8, 13]

# lists are 0-indexed, so index 2 is the third element in X
print(X[2])


7

Slicing

Referring to subsets of lists (remember the 0 indexing):


In [3]:
# slicing
y = X[0:2]
print(y)
y = X[:-2]  # equivalent to x[0:4] 
print(y)


[2, 5]
[2, 5, 7, -2, 0]

List operations

Various methods for lists:

Find index of element with value 5


In [4]:
print(X.index(7))


2

Count number of elements in list


In [5]:
print(len(X))


7

Add element to the end of the list


In [6]:
X.append(99)
print(X)


[2, 5, 7, -2, 0, 8, 13, 99]

Insert element at index 2


In [7]:
X.insert(1, 55)
print(X)


[2, 55, 5, 7, -2, 0, 8, 13, 99]

List comprehensions

Convenient way in Python to make lists which are functions of other lists. Note the ** operator is an exponent, so x**2 means $x^2$.

New list is squares of z


In [8]:
z = [x**2 for x in X]
print(z)


[4, 3025, 25, 49, 4, 0, 64, 169, 9801]

New list is True/False if element is >3 or not


In [9]:
z = [x>3 for x in X]
print(z)


[False, True, True, True, False, False, True, True, True]

Dictionaries (Dicts)

Another way of storing data, which can be looked up using keys.


In [10]:
z = {'name':'Gene', 'apples':5, 'oranges':8}
print(z['name'])
print(z['oranges'])
if 'apples' in z:
    print('yes, the key apples is in the dict z')


Gene
8
yes, the key apples is in the dict z

Loops

For-loops are simple, but we will learn powerful ways to avoid them with Numpy, because they are not optimized for speed.


In [11]:
names = ['Alice', 'Bob', 'Carol', 'David']
for name in names:
    print('Hi %s' % name)


Hi Alice
Hi Bob
Hi Carol
Hi David

Get a list of integers between two endpoints with range.


In [12]:
for i in range(5, 9):
    print(i)


5
6
7
8

Functions

A function is a reusable block of code.


In [13]:
def myFunction(myArgument):
    print('Hello '+myArgument)
    
myFunction('Alice')
myFunction('Bob')


Hello Alice
Hello Bob

Classes

Classes bring object-oriented programming to Python.


In [2]:
class MyClass(object):
    def __init__(self, message): # constructor
        self.message = message   # assign local variable in object
    
    def print_message(self, n_times=2):
        for i in range(n_times):
            print('%s' % self.message)

M = MyClass('Hello from ml4a!')
M.print_message(3)


Hello from ml4a!
Hello from ml4a!
Hello from ml4a!

Libraries

There are many libraries avaialble for Python for various functions.

Let's import two libraries: math and matplotlib.pyplot (alias to plt). Let's use the math function to calculate the cosine of 1.


In [17]:
import matplotlib.pyplot as plt
import math

z = math.cos(1)
print(z)


0.5403023058681398

Plotting

Let's plot our sine curve. We'll be plotting a lot to make concepts more visually clear in the future.


In [18]:
X = [0.1*x for x in range(-50,50)]
Y = [math.sin(x) for x in X]

# make the figure
plt.figure(figsize=(6,6))
plt.plot(X, Y)
plt.xlabel('x')
plt.ylabel('y = sin(x)')
plt.title('My plot title')


Out[18]:
<matplotlib.text.Text at 0x109130860>