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.
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
2 + 3
Division
10 / 3
Exponentiation
Double asterisk (**) means exponentiation, i.e. 2**3 = $2^3$
2**3
Subtraction and Multiplication
10 - 4 * 2
Brackets
(10 - 4) * 2
Create variables and use them to store numbers or other kinds of data. Print their value using the print()
function.
a = 2
b = 3
c = a + b
print(a)
print(c)
print(b - a)
Text data is stored as a 'string' and can be saved to a variable just like numbers.
'Hello World'
greeting = 'Hello World'
print(greeting)
# How long is the string, including letters and spaces?
len(greeting)
# Make all lowercase
greeting.lower()
# Make all uppercase
greeting.upper()
sentence = 'The date today is May 21, 2019.'
# Split the sentence on every comma
sentence.split(',')
# Insert a variable into a string
name = 'Emily'
print('My name is {0}'.format(name))
# 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))
# Combine strings
first = 'Hello'
last = 'World'
print(first + last)
# A space is also a string. Combine three strings together
print(first + ' ' + last)
Lists are another data structure in Python and are identified with square brackets. List items are separated by commas: [a, b, c, ...]
.
mylist = [1, 2, 3, 4, 5]
# How long is my list?
len(mylist)
# Python indexes starting at zero. Retrieve the first item in my list:
mylist[0]
# Get the second item in my list
mylist[1]
# Get the last item in my list
mylist[-1]
# Get items indexed 0 to 3
mylist[0:3]
# Get items indexed 2 to 4
mylist[2:4]
# Get the first 4 items
mylist[:4]
# Get items indexed from 3 onwards
mylist[3:]
# Get every second item in my list
mylist[::2]
# Get all items in my list in reverse order
mylist[::-1]
# Append the number 6 to the end of my list
mylist.append(6)
print(mylist)
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.
person = {'name': 'Sam', 'age': 22, 'weight': 170.2}
print(person)
person['name']
person['age']
person.keys()
person.values()
person.items()
a = (1, 2, 3) # is a tuple
b = [1, 2, 3] # is a list
print(a)
print(b)
Main difference: items in a tuple can't be modified
a[1] = 7
b[1] = 7
print(b)
When to use tuples: Use tuples for groupings of items that go together and shouldn't be changed.
account = ('admin', 'john.smith@company.com', '12345')
username, email, password = account
print(email)
Loops allow you to perform repeated steps.
for i in [1, 2, 3, 4, 5]:
print(i)
for i in range(5):
print(i)
value = 1
limit = 50
while value < limit:
value = value*2
print(value)
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.
greeting = 'Hello'
if greeting == 'Aloha':
print('Aloha')
else:
print('Hi')
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.
sleepy = False
if sleepy:
print('Drink coffee')
a = True
b = True
a and b
a = True
b = False
a and b
a or b
a = False
b = False
a and b
not a and not b
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
a = [2*i for i in range(5)]
print(a)
The above could also be expressed as a for loop:
a = []
for i in range(5):
a.append(2*i)
print(a)
Find common numbers from two list using for loop
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
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:
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)
Python let's you define functions that encapsulate a set of instructions, taking inputs and returning outputs.
def square(x):
return x**2
square(3)
def greet_me(name):
greeting = 'Hello ' + name + '!'
return greeting
greet_me('Mikhail')
filename = 'Data/sonnet33.txt'
file = open(filename, 'r')
sonnet = file.readlines()
file.close()
print(sonnet)
for i in range(len(sonnet)):
print(sonnet[i])
# 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.
print(mobydick)
Let's write the text line by line to a file called mobydick.txt
.
with open('Data/mobydick.txt', 'w') as file:
for line in mobydick:
file.write(line)
Let's check to make sure...
with open('Data/mobydick.txt', 'r') as file:
lines = file.readlines()
print(lines)
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.
# 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.
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.
numpy
¶import numpy as np
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
circle_area(10)
circumference(10)
matplotlib
¶Use the most popular plotting library to make some charts in Python.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [1, 9, 5, 7, 8]
plt.plot(x, y)
x = np.linspace(0, 5, 20)
y = circle_area(x)
print(x)
print(y)
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')
microsoft = si.get_data('msft' , start_date = '01/01/1999')
x = microsoft.index.values
y = microsoft['close'].values
plt.plot(x, y)