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.
A review of core concepts in Python follows:
In [1]:
myVariable = 'hello world'
print(myVariable)
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])
In [3]:
# slicing
y = X[0:2]
print(y)
y = X[:-2] # equivalent to x[0:4]
print(y)
Find index of element with value 5
In [4]:
print(X.index(7))
Count number of elements in list
In [5]:
print(len(X))
Add element to the end of the list
In [6]:
X.append(99)
print(X)
Insert element at index 2
In [7]:
X.insert(1, 55)
print(X)
New list is squares of z
In [8]:
z = [x**2 for x in X]
print(z)
New list is True/False if element is >3 or not
In [9]:
z = [x>3 for x in X]
print(z)
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')
In [11]:
names = ['Alice', 'Bob', 'Carol', 'David']
for name in names:
print('Hi %s' % name)
Get a list of integers between two endpoints with range.
In [12]:
for i in range(5, 9):
print(i)
In [13]:
def myFunction(myArgument):
print('Hello '+myArgument)
myFunction('Alice')
myFunction('Bob')
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)
In [17]:
import matplotlib.pyplot as plt
import math
z = math.cos(1)
print(z)
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]: