Introduction to Python

Python is a general-purpose programming language that is designed to be easy to read and easy to learn. It allows you to express ideas in relatively few lines of code. The various core Python packages, along with those written by the community, extend Python's capabilities immensely.

This is a Jupyter Notebook, an open-source web application that allows you to run Python code directly inside your web browser. It combines live code with narrative text. The Notebook is divided into "cells". These can contain code or plain text formatted in Markdown.

Numbers

Python can function just like a calculator. You can use it to do some simple arithmetic.

Execute code cells by pressing Shift-Enter on your keyboard with the code cell selected. The output is shown immediately underneath.

Addition

In [ ]:
2 + 3

Division

In [ ]:
10 / 3

Exponentiation

Double asterisk (**) means exponentiation, i.e. 2**3 = $2^3$

In [ ]:
2**3

Subtraction and Multiplication

In [ ]:
10 - 4 * 2

Brackets

In [ ]:
(10 - 4) * 2

Variables

Create variables and use them to store numbers or other kinds of data. Print their value using the print() function.

In [ ]:
a = 2
b = 3
c = a + b
In [ ]:
print(a)
In [ ]:
print(c)
In [ ]:
print(b - a)

Strings

Text data is stored as a 'string' and can be saved to a variable just like numbers.

In [ ]:
'Hello World'
In [ ]:
greeting = 'Hello World'
In [ ]:
print(greeting)
In [ ]:
# How long is the string, including letters and spaces?
len(greeting)
In [ ]:
# Make all lowercase
greeting.lower()
In [ ]:
# Make all uppercase
greeting.upper()
In [ ]:
sentence = 'The date today is May 21, 2019.'
In [ ]:
# Split the sentence on every comma
sentence.split(',')
In [ ]:
# Insert a variable into a string
name = 'Emily'

print('My name is {0}'.format(name))
In [ ]:
# Insert a variable in multiple places of a string and perform some arithmetic in the process
age = 30

print('I am {0} years old. Tomorrow is my birthday. I will be {1}.'.format(age, age+1))
In [ ]:
# Combine strings
first = 'Hello'
last = 'World'

print(first + last)
In [ ]:
# A space is also a string. Combine three strings together
print(first + ' ' + last)

Lists

Lists are another data structure in Python and are identified with square brackets. List items are separated by commas: [a, b, c, ...].

In [ ]:
mylist = [1, 2, 3, 4, 5]
In [ ]:
# How long is my list?
len(mylist)
In [ ]:
# Python indexes starting at zero. Retrieve the first item in my list:
mylist[0]
In [ ]:
# Get the second item in my list
mylist[1]
In [ ]:
# Get the last item in my list
mylist[-1]
In [ ]:
# Get items indexed 0 to 3
mylist[0:3]
In [ ]:
# Get items indexed 2 to 4
mylist[2:4]
In [ ]:
# Get the first 4 items
mylist[:4]
In [ ]:
# Get items indexed from 3 onwards
mylist[3:]
In [ ]:
# Get every second item in my list
mylist[::2]
In [ ]:
# Get all items in my list in reverse order
mylist[::-1]
In [ ]:
# Append the number 6 to the end of my list
mylist.append(6)
In [ ]:
print(mylist)

Dictionaries

A Python dictionary is a way of storing named items together. The items in a dictionary are called key-value pairs. The 'key' is the name of the item. The 'value' can be any data type or object and can be mixed within the same dictionary.

In [ ]:
person = {'name': 'Sam', 'age': 22, 'weight': 170.2}
In [ ]:
print(person)
In [ ]:
person['name']
In [ ]:
person['age']
In [ ]:
person.keys()
In [ ]:
person.values()
In [ ]:
person.items()

Tuples

In [ ]:
a = (1, 2, 3) # is a tuple
b = [1, 2, 3] # is a list
In [ ]:
print(a)
print(b)

Main difference: items in a tuple can't be modified

In [ ]:
a[1] = 7
In [ ]:
b[1] = 7

print(b)

When to use tuples: Use tuples for groupings of items that go together and shouldn't be changed.

In [ ]:
account = ('admin', 'john.smith@company.com', '12345')
In [ ]:
username, email, password = account
In [ ]:
print(email)

Loops

Loops allow you to perform repeated steps.

In [ ]:
for i in [1, 2, 3, 4, 5]:
    print(i)
In [ ]:
for i in range(5):
    print(i)
In [ ]:
value = 1
limit = 50

while value < limit:
    value = value*2
    print(value)

Conditionals

You can control the flow of code using if statements. In Python there is no need to write then. You end your if statement with a colon (:), and then start your next line with an indent. The indented code beneath an if statement is how Python knows what code to execute if the if statement evaluates as true.

The other conditional structures, like else and elif (else-if) work the same way.

In [ ]:
greeting = 'Hello'

if greeting == 'Aloha':
    print('Aloha')
else:
    print('Hi')
In [ ]:
today = 'Tuesday'

if today is 'Tuesday':
    print('It is Tuesday')
elif today is 'Wednesday':
    print('Today is Wednesday')
else:
    print('Today is {}'.format(today))

True and False are special keywords in Python and must be written in the title case.

In [ ]:
sleepy = False

if sleepy:
    print('Drink coffee')
    
In [ ]:
a = True
b = True

a and b
In [ ]:
a = True
b = False

a and b
In [ ]:
a or b
In [ ]:
a = False
b = False

a and b
In [ ]:
not a and not b

Fancy Trick: List Comprehension

If you're creating a list or similar object that has a repeating pattern, you can use a trick called list comprehension. It is a more compact way of expressing an idea that would otherwise take a for-loop to express.

The examples below come from: https://hackernoon.com/list-comprehension-in-python-8895a785550b

In [ ]:
a = [2*i for i in range(5)]

print(a)

The above could also be expressed as a for loop:

In [ ]:
a = []
for i in range(5):
    a.append(2*i)
    
print(a)

Find common numbers from two list using for loop

In [ ]:
list_a = [1, 2, 3, 4]
list_b = [2, 3, 4, 5]

common_num = []

for a in list_a:
    for b in list_b:
        if a == b:
            common_num.append(a)

print(common_num)

Find common numbers from two list using list comprehension

In [ ]:
list_a = [1, 2, 3, 4]
list_b = [2, 3, 4, 5]

common_num = [a for a in list_a for b in list_b if a == b]

print(common_num)

Return numbers from the list which are not equal as tuple:

In [ ]:
list_a = [1, 2, 3]
list_b = [2, 7]

different_num = [(a, b) for a in list_a for b in list_b if a != b]

print(different_num)

Functions

Python let's you define functions that encapsulate a set of instructions, taking inputs and returning outputs.

In [ ]:
def square(x):
    return x**2
In [ ]:
square(3)
In [ ]:
def greet_me(name):
    greeting = 'Hello ' + name + '!'
    return greeting
In [ ]:
greet_me('Mikhail')

Reading and Writing Files

Reading

In [ ]:
filename = 'Data/sonnet33.txt'

file = open(filename, 'r')
sonnet = file.readlines()
file.close()
In [ ]:
print(sonnet)
In [ ]:
for i in range(len(sonnet)):
    print(sonnet[i])

Writing a File

In [ ]:
# The famous first paragraph from Herman Melville's classic, Moby Dick; or, The Whale.
mobydick = "Call me Ishmael. Some years ago- never mind how long precisely- \
            having little or no money in my purse, and nothing particular to \
            interest me on shore, I thought I would sail about a little and \
            see the watery part of the world. It is a way I have of driving \
            off the spleen and regulating the circulation. Whenever I find \
            myself growing grim about the mouth; whenever it is a damp, \
            drizzly November in my soul; whenever I find myself involuntarily \
            pausing before coffin warehouses, and bringing up the rear of every \
            funeral I meet; and especially whenever my hypos get such an upper \
            hand of me, that it requires a strong moral principle to prevent me \
            from deliberately stepping into the street, and methodically \
            knocking people's hats off- then, I account it high time to get to \
            sea as soon as I can. This is my substitute for pistol and ball. \
            With a philosophical flourish Cato throws himself upon his sword; \
            I quietly take to the ship. There is nothing surprising in this. If \
            they but knew it, almost all men in their degree, some time or other, \
            cherish very nearly the same feelings towards the ocean with me.".split('            ')

# Above, we split the text block on the long chunk of white space I used at the beginning
# of most lines in order to align the text

We use Python's line continuation character, \, to split a very long string across multiple lines inside the Notebook cell. However, because we aligned the next, we introduced a lot of white space at the beginning of each line. The .split() method breaks the long string into a list of a shorter strings, splitting on the long whitespace.

In [ ]:
print(mobydick)

Let's write the text line by line to a file called mobydick.txt.

In [ ]:
with open('Data/mobydick.txt', 'w') as file:
    for line in mobydick:
        file.write(line)

Let's check to make sure...

In [ ]:
with open('Data/mobydick.txt', 'r') as file:
    lines = file.readlines()
    
print(lines)

Accessing the Internet

For this example, we will use the yahoo_fin Python package, which scrapes data from Yahoo Finance. It can do many impressive things, but we're only going to use it to fetch the current stock price of a few companies. We need to look these up by their ticker symbols.

  • MSFT = Microsoft
  • AAPL = Apple
  • NFLX = Netflix
In [ ]:
# stock_info is a submodule of the Yahoo Finance package.
# We're going to import it by itself and assigned it to 
# the variable `si`
from yahoo_fin import stock_info as si

stocks = ['MSFT', 'AAPL', 'NFLX']

for stock in stocks:
    price = si.get_live_price(stock)
    print('{}: ${:.2f}'.format(stock, price))

The syntax {:.2f} might seem a bit confusing, but we're just including some formatting instructions: present the stock price to two decimal places.

Python Packages

In the last example we imported a package called yahoo_fin that accessed Yahoo Finance. Python has many packages you can install that extend Python's capabilities tremendously. Anybody can write their own packages and submit them to the community.

Working with Numerical Data using numpy

In [ ]:
import numpy as np
In [ ]:
def circle_area(radius):
    # The area of a circle of a circle is pi times the radius squared.
    return np.pi * radius**2

def circumference(radius):
    # The circumference of a circle is twice the radius times pi.
    return 2 * np.pi * radius
In [ ]:
circle_area(10)
In [ ]:
circumference(10)

Making Pretty Charts with matplotlib

Use the most popular plotting library to make some charts in Python.

In [ ]:
import matplotlib.pyplot as plt
In [ ]:
x = [1, 2, 3, 4, 5]
y = [1, 9, 5, 7, 8]

plt.plot(x, y)
In [ ]:
x = np.linspace(0, 5, 20)
y = circle_area(x)

print(x)

print(y)
In [ ]:
plt.plot(x, y)

axes = plt.gca()
axes.set_title('Circle Area as a Function of Radius')
axes.set_xlabel('Radius')
axes.set_ylabel('Area')
In [ ]:
microsoft = si.get_data('msft' , start_date = '01/01/1999')
In [ ]:
x = microsoft.index.values
y = microsoft['close'].values

plt.plot(x, y)
In [ ]: