In [1]:
from IPython.display import HTML
import requests
HTML(requests.get("https://git.io/fh5WI").text)
Out[1]:
go top

1. Jupyter Notebook and JupyterLab


Jupyter Notebook (used in this workshop)

  • Has been around since 2011.
  • Works with one notebook file at a time.

Jupyter Lab

  • Eventual successor to Jupyter Notebook.
  • The same basic functionality as the Notebook, but more flexible environment - can work with multiple notebooks/files side by side.
  • Still in beta.
  • Works fine most of the time, but some notebook functionality not quite there yet.
go top

2. Notebook Basics


2.1 Markdown Cells

Shift-Enter to render.

This is a markdown cell.

Header

Subheader

Subsubheader

italics or boldface

Lists:

  • item 1
  • item 2
  • item 3

This is a link

Some mathematics (uses LaTeX syntax):

$$\int x^2 dx = \frac{1}{3} x^3 + C$$
go top

3.2 Code Cells

Shift-Enter to execute.

In [4]:
3*5
Out[4]:
15
In [4]:
print("hello!")
hello!
go top

3. Python Basics


3.1 Numbers and Arithmetics

In [2]:
2+3
Out[2]:
5
In [3]:
2*3
Out[3]:
6
In [33]:
2**3
Out[33]:
8
In [2]:
2.0*3.0 
Out[2]:
6.0
Integers can be of an arbitrary size:
In [122]:
2**10000
Out[122]:
19950631168807583848837421626835850838234968318861924548520089498529438830221946631919961684036194597899331129423209124271556491349413781117593785932096323957855730046793794526765246551266059895520550086918193311542508608460618104685509074866089624888090489894838009253941633257850621568309473902556912388065225096643874441046759871626985453222868538161694315775629640762836880760732228535091641476183956381458969463899410840960536267821064621427333394036525565649530603142680234969400335934316651459297773279665775606172582031407994198179607378245683762280037302885487251900834464581454650557929601414833921615734588139257095379769119277800826957735674444123062018757836325502728323789270710373802866393031428133241401624195671690574061419654342324638801248856147305207431992259611796250130992860241708340807605932320161268492288496255841312844061536738951487114256315111089745514203313820202931640957596464756010405845841566072044962867016515061920631004186422275908670900574606417856951911456055068251250406007519842261898059237118054444788072906395242548339221982707404473162376760846613033778706039803413197133493654622700563169937455508241780972810983291314403571877524768509857276937926433221599399876886660808368837838027643282775172273657572744784112294389733810861607423253291974813120197604178281965697475898164531258434135959862784130128185406283476649088690521047580882615823961985770122407044330583075869039319604603404973156583208672105913300903752823415539745394397715257455290510212310947321610753474825740775273986348298498340756937955646638621874569499279016572103701364433135817214311791398222983845847334440270964182851005072927748364550578634501100852987812389473928699540834346158807043959118985815145779177143619698728131459483783202081474982171858011389071228250905826817436220577475921417653715687725614904582904992461028630081535583308130101987675856234343538955409175623400844887526162643568648833519463720377293240094456246923254350400678027273837755376406726898636241037491410966718557050759098100246789880178271925953381282421954028302759408448955014676668389697996886241636313376393903373455801407636741877711055384225739499110186468219696581651485130494222369947714763069155468217682876200362777257723781365331611196811280792669481887201298643660768551639860534602297871557517947385246369446923087894265948217008051120322365496288169035739121368338393591756418733850510970271613915439590991598154654417336311656936031122249937969999226781732358023111862644575299135758175008199839236284615249881088960232244362173771618086357015468484058622329792853875623486556440536962622018963571028812361567512543338303270029097668650568557157505516727518899194129711337690149916181315171544007728650573189557450920330185304847113818315407324053319038462084036421763703911550639789000742853672196280903477974533320468368795868580237952218629120080742819551317948157624448298518461509704888027274721574688131594750409732115080498190455803416826949787141316063210686391511681774304792596709376
Size of floats is limited:
In [3]:
2.0**10000
---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
<ipython-input-3-c0a738458c2d> in <module>
----> 1 2.0**10000

OverflowError: (34, 'Result too large')
Modulus:
In [4]:
19%5
Out[4]:
4
In [5]:
20%5
Out[5]:
0
go top

3.2 Variable assignments

In [8]:
a = 3
b = 4
In [9]:
a+b
Out[9]:
7
In [10]:
a,b,c = 4, 5, 6 
In [11]:
a
Out[11]:
4
In [54]:
b
Out[54]:
5
In [55]:
c
Out[55]:
6
In [62]:
a, b
Out[62]:
(4, 5)
In [63]:
a, b = b, a
In [64]:
a, b
Out[64]:
(5, 4)
go top

3.3 Importing Modules


Built-in functionality of Python is limited. E.g. no trigonometric functions:

In [7]:
sin(0)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-7-afbcc558f753> in <module>
----> 1 sin(0)

NameError: name 'sin' is not defined
Good news: There are external libraries (modules) suited for almost any task.
In [5]:
import math
In [66]:
dir(math)
Out[66]:
['__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'acos',
 'acosh',
 'asin',
 'asinh',
 'atan',
 'atan2',
 'atanh',
 'ceil',
 'copysign',
 'cos',
 'cosh',
 'degrees',
 'e',
 'erf',
 'erfc',
 'exp',
 'expm1',
 'fabs',
 'factorial',
 'floor',
 'fmod',
 'frexp',
 'fsum',
 'gamma',
 'gcd',
 'hypot',
 'inf',
 'isclose',
 'isfinite',
 'isinf',
 'isnan',
 'ldexp',
 'lgamma',
 'log',
 'log10',
 'log1p',
 'log2',
 'modf',
 'nan',
 'pi',
 'pow',
 'radians',
 'remainder',
 'sin',
 'sinh',
 'sqrt',
 'tan',
 'tanh',
 'tau',
 'trunc']
In [6]:
help(math)
Help on module math:

NAME
    math

MODULE REFERENCE
    https://docs.python.org/3.7/library/math
    
    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    This module is always available.  It provides access to the
    mathematical functions defined by the C standard.

FUNCTIONS
    acos(x, /)
        Return the arc cosine (measured in radians) of x.
    
    acosh(x, /)
        Return the inverse hyperbolic cosine of x.
    
    asin(x, /)
        Return the arc sine (measured in radians) of x.
    
    asinh(x, /)
        Return the inverse hyperbolic sine of x.
    
    atan(x, /)
        Return the arc tangent (measured in radians) of x.
    
    atan2(y, x, /)
        Return the arc tangent (measured in radians) of y/x.
        
        Unlike atan(y/x), the signs of both x and y are considered.
    
    atanh(x, /)
        Return the inverse hyperbolic tangent of x.
    
    ceil(x, /)
        Return the ceiling of x as an Integral.
        
        This is the smallest integer >= x.
    
    copysign(x, y, /)
        Return a float with the magnitude (absolute value) of x but the sign of y.
        
        On platforms that support signed zeros, copysign(1.0, -0.0)
        returns -1.0.
    
    cos(x, /)
        Return the cosine of x (measured in radians).
    
    cosh(x, /)
        Return the hyperbolic cosine of x.
    
    degrees(x, /)
        Convert angle x from radians to degrees.
    
    erf(x, /)
        Error function at x.
    
    erfc(x, /)
        Complementary error function at x.
    
    exp(x, /)
        Return e raised to the power of x.
    
    expm1(x, /)
        Return exp(x)-1.
        
        This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
    
    fabs(x, /)
        Return the absolute value of the float x.
    
    factorial(x, /)
        Find x!.
        
        Raise a ValueError if x is negative or non-integral.
    
    floor(x, /)
        Return the floor of x as an Integral.
        
        This is the largest integer <= x.
    
    fmod(x, y, /)
        Return fmod(x, y), according to platform C.
        
        x % y may differ.
    
    frexp(x, /)
        Return the mantissa and exponent of x, as pair (m, e).
        
        m is a float and e is an int, such that x = m * 2.**e.
        If x is 0, m and e are both 0.  Else 0.5 <= abs(m) < 1.0.
    
    fsum(seq, /)
        Return an accurate floating point sum of values in the iterable seq.
        
        Assumes IEEE-754 floating point arithmetic.
    
    gamma(x, /)
        Gamma function at x.
    
    gcd(x, y, /)
        greatest common divisor of x and y
    
    hypot(x, y, /)
        Return the Euclidean distance, sqrt(x*x + y*y).
    
    isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
        Determine whether two floating point numbers are close in value.
        
          rel_tol
            maximum difference for being considered "close", relative to the
            magnitude of the input values
          abs_tol
            maximum difference for being considered "close", regardless of the
            magnitude of the input values
        
        Return True if a is close in value to b, and False otherwise.
        
        For the values to be considered close, the difference between them
        must be smaller than at least one of the tolerances.
        
        -inf, inf and NaN behave similarly to the IEEE 754 Standard.  That
        is, NaN is not close to anything, even itself.  inf and -inf are
        only close to themselves.
    
    isfinite(x, /)
        Return True if x is neither an infinity nor a NaN, and False otherwise.
    
    isinf(x, /)
        Return True if x is a positive or negative infinity, and False otherwise.
    
    isnan(x, /)
        Return True if x is a NaN (not a number), and False otherwise.
    
    ldexp(x, i, /)
        Return x * (2**i).
        
        This is essentially the inverse of frexp().
    
    lgamma(x, /)
        Natural logarithm of absolute value of Gamma function at x.
    
    log(...)
        log(x, [base=math.e])
        Return the logarithm of x to the given base.
        
        If the base not specified, returns the natural logarithm (base e) of x.
    
    log10(x, /)
        Return the base 10 logarithm of x.
    
    log1p(x, /)
        Return the natural logarithm of 1+x (base e).
        
        The result is computed in a way which is accurate for x near zero.
    
    log2(x, /)
        Return the base 2 logarithm of x.
    
    modf(x, /)
        Return the fractional and integer parts of x.
        
        Both results carry the sign of x and are floats.
    
    pow(x, y, /)
        Return x**y (x to the power of y).
    
    radians(x, /)
        Convert angle x from degrees to radians.
    
    remainder(x, y, /)
        Difference between x and the closest integer multiple of y.
        
        Return x - n*y where n*y is the closest integer multiple of y.
        In the case where x is exactly halfway between two multiples of
        y, the nearest even value of n is used. The result is always exact.
    
    sin(x, /)
        Return the sine of x (measured in radians).
    
    sinh(x, /)
        Return the hyperbolic sine of x.
    
    sqrt(x, /)
        Return the square root of x.
    
    tan(x, /)
        Return the tangent of x (measured in radians).
    
    tanh(x, /)
        Return the hyperbolic tangent of x.
    
    trunc(x, /)
        Truncates the Real x to the nearest Integral toward 0.
        
        Uses the __trunc__ magic method.

DATA
    e = 2.718281828459045
    inf = inf
    nan = nan
    pi = 3.141592653589793
    tau = 6.283185307179586

FILE
    /anaconda3/lib/python3.7/lib-dynload/math.cpython-37m-darwin.so


In [67]:
math.pi
Out[67]:
3.141592653589793
In [69]:
math.sin(math.pi)
Out[69]:
1.2246467991473532e-16

More convenient ways to import:


1. Give a module a nickname:
In [12]:
import math as m
In [71]:
m.sin(m.pi)
Out[71]:
1.2246467991473532e-16
2. Import some module content directly:
In [2]:
from math import sin, pi
In [3]:
sin(pi)
Out[3]:
1.2246467991473532e-16
3. Import the whole module content directly (not recommended):
In [5]:
from math import *
In [6]:
cos(pi)
Out[6]:
-1.0
In [7]:
log(pi)
Out[7]:
1.1447298858494002
go top

3.4 Text Strings


  • In either single or double quotes.
  • In triple quotes for multiline strings.
In [25]:
a = 'Hello'
print(a)
Hello
In [26]:
b = "world!"
print(b)
world!
In [22]:
c = '''more than 
one line'''
print(c)
more than 
one line
String concatenation:
In [27]:
c = a + b
print(c)
Helloworld!
In [30]:
print(10*a)
HelloHelloHelloHelloHelloHelloHelloHelloHelloHello
f-strings:
In [85]:
a = 1
b = 2
c = a + b

s = f"{a} plus {b} equals {c}"
print(s)
1 plus 2 equals 3
go top

3.5 if/then/else


if condition: 
    do this 
    do this
    do this
else: 
    do this 
    do this

Note: In Python code blocks are defined by their indentation.
In [31]:
x = 101

if x > 100:
    print('big number')
print('Done!')
big number
Done!
In [2]:
x = 0

if x > 100:
    print("big number")
else:
    print("small number")
print("Done!")
small number
Done!
go top

3.6 Booleans

In [3]:
10 > 5
Out[3]:
True
In [4]:
10 == 5
Out[4]:
False
In [12]:
10 != 5
Out[12]:
True
In [27]:
(10 > 5) or (10 < 5) 
Out[27]:
True
In [28]:
(10 > 5) and (10 < 5) 
Out[28]:
False
Note:
  • Non-zero numbers and non-empty strings are interpreted as True.
  • Zero and an empty string give False.
In [16]:
x = 7

if x:
    print("Yes!")
else:
    print("No!")
Yes!
go top

3.7 "while" loops

while condition: 
    do this 
    do this
    do this
In [39]:
i = 1
while i < 5:
    print(i*10)
    i += 1
print("Done!")
10
20
30
40
Done!
In [3]:
r = input("Delete file? (yes/no): ")

while True:
    if  r == 'no':
        print("Cancelled")
        break
    elif r == 'yes': 
        print("File deleted")
        break
    else:
        print(f'invalid option: "{r}"')
        r = input("Delete file? (yes/no): ")
Delete file? (yes/no): y
invalid option: "y"
Delete file? (yes/no): n
invalid option: "n"
Delete file? (yes/no): yes
File deleted
go top

3.8 Lists and "for" Loops


for item in list_of_items: 
    do this 
    do this
    do this
  • A list is an ordered collection of objects of arbitrary types.
  • It is created by enclosing objects in square brackets:
mylist = [a, b, c] 
In [5]:
mylist = [3, 5.1, "Hello", True]
mylist
Out[5]:
[3, 5.1, 'Hello', True]
In [6]:
for x in mylist:
    print(2*x)
6
10.2
HelloHello
2
Note:

For all practical purposes True and False are the same as 1 and 0:

In [70]:
True == 1
Out[70]:
True
In [71]:
False == 0
Out[71]:
True

Accessing list items (indexing starts at 0):

In [245]:
mylist
Out[245]:
[3, 5.1, 'Hello', True]
In [246]:
mylist[0]
Out[246]:
3
In [247]:
mylist[2]
Out[247]:
'Hello'

Negative indexing counts from the end:

In [254]:
mylist[-1]
Out[254]:
True
In [255]:
mylist[-2]
Out[255]:
'Hello'

List concatenation:

In [283]:
x = [1, 2, 3] + ['a', 'b', 'c']
x
Out[283]:
[1, 2, 3, 'a', 'b', 'c']

Appending an element to a list:

In [284]:
x
Out[284]:
[1, 2, 3, 'a', 'b', 'c']
In [285]:
x.append('Hello')
x
Out[285]:
[1, 2, 3, 'a', 'b', 'c', 'Hello']
go top

3.9 Lists Slicing


  • Creates a sublist of a list.
mylist[start : stop]
mylist[start : stop : step]
In [259]:
numbers = list(range(20))
numbers
Out[259]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
In [261]:
numbers[5:15]
Out[261]:
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
In [262]:
numbers[5:15:3]
Out[262]:
[5, 8, 11, 14]
Strings can be sliced too:
In [17]:
s = "University at Buffalo"
In [18]:
s[4:16]
Out[18]:
'ersity at Bu'
In [19]:
s[::2]
Out[19]:
'Uiest tBfao'
go top

3.10 Lists Comprehensions


  • Creates a new list from a given list.
[f(x) for x in mylist]
[f(x) for x in mylist if condition]
In [271]:
numbers = list(range(10))
numbers
Out[271]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [272]:
squares = [x**2 for x in numbers]
squares
Out[272]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In [274]:
even_squares = [x**2 for x in numbers if x%2 == 0]
even_squares
Out[274]:
[0, 4, 16, 36, 64]

The same with the "for" loop:

In [276]:
even_squares2 = []
for x in numbers:
    if x%2 == 0:
        even_squares2.append(x**2)

even_squares2
Out[276]:
[0, 4, 16, 36, 64]

Example: FizzBuzz

  Write a program that prints the numbers from 1 to 100. But:
  • for multiples of 3 print “Fizz” instead of the number
  • for the multiples of 5 print “Buzz”
  • for multiples of both 3 and 5 print “FizzBuzz”.
In [315]:
fb = [("Fizz" if x%3==0 else "") + ("Buzz" if x%5==0 else "") or x for x in range(1, 20) ]

for i in fb: 
    print(i)
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
In [5]:
x = 5
("Fizz" if x%3==0 else "")
Out[5]:
''
In [9]:
x = 15
("Fizz" if x%3==0 else "") + ("Buzz" if x%5==0 else "")
Out[9]:
'FizzBuzz'

Note: or and and return the value of the last expression they evaluate:

In [300]:
a = "hi"
b = "hello"

a or b
Out[300]:
'hi'
In [97]:
x = 10
x or 2/0
Out[97]:
10
In [23]:
x = 15
("Fizz" if x%3==0 else "") + ("Buzz" if x%5==0 else "") or x
Out[23]:
'FizzBuzz'
go top

3.11 Dictionaries


  • Collections of values indexed by keys:
my_dictionary = {key1:value1, key2:value2, ...}
In [22]:
game_scores = {}
In [23]:
game_scores["John"] = 100
game_scores["Ann"] = 120 
game_scores["Tom"] = 70
game_scores
Out[23]:
{'John': 100, 'Ann': 120, 'Tom': 70}
Values can be retrieved and modified by key:
In [24]:
game_scores["Ann"]
Out[24]:
120
In [25]:
game_scores["Ann"] = 130
game_scores
Out[25]:
{'John': 100, 'Ann': 130, 'Tom': 70}

Adding new records:

In [27]:
game_scores["Beth"] = 0
game_scores
Out[27]:
{'John': 100, 'Ann': 130, 'Tom': 70, 'Beth': 0}
Iteration on keys:
In [28]:
for name in game_scores:
    print(name, game_scores[name])
John 100
Ann 130
Tom 70
Beth 0
go top

3.12 Functions


def foo(arg1 , arg2, ...):
    do this 
    do this
    return this
In [31]:
def add(x, y):
    z = x+y
    return z
In [32]:
add(2, 3)
Out[32]:
5
In [33]:
add("hello ", "world!")
Out[33]:
'hello world!'
In [45]:
from time import sleep

def timer(seconds, message = "Time's up!"):
    for t in range(seconds,0,-1):
        print(t)
        sleep(1)
    print(message)
In [41]:
timer(10)
10
9
8
7
6
5
4
3
2
1
Time's up!
In [42]:
timer(5, message = "Boom!")
5
4
3
2
1
Boom!
go top

3.13 Classes and Objects


class MyClass:
    statement
    statement
    statement

x = MyClass()
In [12]:
class Player:

    name = None
    score = 0
In [17]:
class Player:

    name = None
    score = 0
    
    def bonus(self, percent):
        self.score = int(self.score * (1 + percent/100))
    
    def __str__(self):
        return f"Name: {self.name}\nScore: {self.score}"
In [18]:
p = Player()
p.name = "John"
p.score = 10

print(p)
Name: John
Score: 10
In [40]:
p.bonus(50)
In [19]:
print(p)
Name: John
Score: 10
In [21]:
q = Player()
print(q)
Name: None
Score: 0
In [22]:
q.name = "Beth"
q.score = 20
In [23]:
print(q)
Name: Beth
Score: 20
In [24]:
dir(q)
Out[24]:
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'bonus',
 'name',
 'score']
Note: In Python everything is an object.
In [91]:
[1, 2, 3].__class__
Out[91]:
list
In [78]:
dir([1, 2, 3])
Out[78]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']
In [26]:
[1, 2, 3].__add__([4,5])
Out[26]:
[1, 2, 3, 4, 5]