Commit 8c6adbca authored by Ben Glocker's avatar Ben Glocker
Browse files

tutorials 5-7

parent ecec7a38
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Introduction to Python (for Algorithms 2) # Introduction to Python (for Algorithms 2)
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
by *James Booth* and *Ghislain Antony Vaillant* by *James Booth* and *Ghislain Antony Vaillant*
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Disclaimer ### Disclaimer
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
This notebook is by no means a comprehensive introduction to the Python programming language. It covers the essential language features required to implement, test and validate the Algorithms 202 courseworks. It is strongly advised to complement this tutorial with additional reading such as the [official Python documentation](https://docs.python.org/3/), [Python 101](https://leanpub.com/python_101) or the excellent [Hitchhiker's guide to Python](http://docs.python-guide.org/en/latest/). This notebook is by no means a comprehensive introduction to the Python programming language. It covers the essential language features required to implement, test and validate the Algorithms 202 courseworks. It is strongly advised to complement this tutorial with additional reading such as the [official Python documentation](https://docs.python.org/3/), [Python 101](https://leanpub.com/python_101) or the excellent [Hitchhiker's guide to Python](http://docs.python-guide.org/en/latest/).
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Language basics ## Language basics
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Syntax and features ### Syntax and features
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Hello world #### Hello world
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print("Hello, world!") print("Hello, world!")
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Built-in [functions](https://docs.python.org/3/library/functions.html) #### Built-in [functions](https://docs.python.org/3/library/functions.html)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print("Hello, world!") print("Hello, world!")
print("Hello,", "world!") print("Hello,", "world!")
print("{}, {}!".format("Hello", "world")) print("{}, {}!".format("Hello", "world"))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
help(print) help(print)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
type(1.0) type(1.0)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
assert(2 % 2 == 0) assert(2 % 2 == 0)
#assert(2 / 2 == 0) #assert(2 / 2 == 0)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Built-in [types](https://docs.python.org/3/library/stdtypes.html) #### Built-in [types](https://docs.python.org/3/library/stdtypes.html)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Booleans # Booleans
B = True B = True
print(type(B)) print(type(B))
# Numeric types # Numeric types
N = 1 N = 1
print(type(N)) print(type(N))
N = 1.0 N = 1.0
print(type(N)) print(type(N))
N = 1j N = 1j
print(type(N)) print(type(N))
# Strings # Strings
N = "Hello, word" N = "Hello, word"
print(type(N)) print(type(N))
# Lists # Lists
L = [False, 1.0, "Hello"] L = [False, 1.0, "Hello"]
print(type(L)) print(type(L))
# Ranges # Ranges
R = range(10) R = range(10)
print(type(R)) print(type(R))
# None # None
print(type(None)) print(type(None))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Dynamic typing #### Dynamic typing
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
x = 3 # Defines a binding a variable named "x", x = 3 # Defines a binding a variable named "x",
# to an object of type integer with value 3. # to an object of type integer with value 3.
print('x is of type {} with value {}'.format(type(x), x)) print('x is of type {} with value {}'.format(type(x), x))
x = 2.0 # Redefine the binding between "x" and an x = 2.0 # Redefine the binding between "x" and an
# object of type float with value 2.0. # object of type float with value 2.0.
print('x is of type {} with value {}'.format(type(x), x)) print('x is of type {} with value {}'.format(type(x), x))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Strong typing #### Strong typing
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print(1 + '2') # What is the intent here? print(1 + '2') # What is the intent here?
# "Explicit is better than implicit." # "Explicit is better than implicit."
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print(str(1) + '2') # String concatenation. print(str(1) + '2') # String concatenation.
print(1 + int('2')) # Integer summation. print(1 + int('2')) # Integer summation.
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Variables and scopes #### Variables and scopes
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
a = 0 a = 0
if False: if False:
b = 1 b = 1
def my_function(c): def my_function(c):
d = 3 d = 3
print(a) # a is global print(a) # a is global
print(b) # b is global print(b) # b is global
print(c) # c is local print(c) # c is local
print(d) # d is local print(d) # d is local
my_function(2) my_function(2)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Control flow ### Control flow
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### `if` statements #### `if` statements
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# simple branching # simple branching
if condition: if condition:
do_something() do_something()
# 2-way branching # 2-way branching
if condition: if condition:
do_something() do_something()
else: else:
do_other_thing() do_other_thing()
# switch-case style # switch-case style
if condition: if condition:
do_something() do_something()
elif other_condition: elif other_condition:
do_other_thing() do_other_thing()
else: else:
do_default_thing() do_default_thing()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### `while` statements #### `while` statements
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# loop until # loop until
while condition: while condition:
do_something() do_something()
# loop until with break clause # loop until with break clause
while condition: while condition:
do_something() do_something()
if specific_condition: if specific_condition:
break # exit while loop regardless break # exit while loop regardless
do_other_thing() do_other_thing()
# loop until with break clause # loop until with break clause
while condition: while condition:
do_something() do_something()
if specific_condition: if specific_condition:
continue # loop-back regardless continue # loop-back regardless
do_other_thing() do_other_thing()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### `for` statements #### `for` statements
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
for n in range(10): for n in range(10):
print(n) print(n)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
numbers = [1, 2, 3] numbers = [1, 2, 3]
for number in numbers: for number in numbers:
print(number) print(number)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
ingredients = ['carrots', 'leeks', 'potatoes'] ingredients = ['carrots', 'leeks', 'potatoes']
for index, ingredient in enumerate(ingredients): for index, ingredient in enumerate(ingredients):
print(index, ingredient) print(index, ingredient)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Data structures ### Data structures
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Common concepts #### Common concepts
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# literals # literals
vowels = ['a', 'e', 'i', 'o', 'u', 'y'] vowels = ['a', 'e', 'i', 'o', 'u', 'y']
print('vowels: {}'.format(vowels)) print('vowels: {}'.format(vowels))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# indexing # indexing
print('the first vowel is: ' + vowels[0]) print('the first vowel is: ' + vowels[0])
print('the last vowel is: ' + vowels[-1]) print('the last vowel is: ' + vowels[-1])
print('the second-to-last vowel is: ' + vowels[-2]) print('the second-to-last vowel is: ' + vowels[-2])
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# slicing # slicing
print('first three: {}'.format(vowels[:3])) print('first three: {}'.format(vowels[:3]))
print('last two: {}'.format(vowels[-2:])) print('last two: {}'.format(vowels[-2:]))
print('middle ones: {}'.format(vowels[1:-1])) print('middle ones: {}'.format(vowels[1:-1]))
print('one each two: {}'.format(vowels[::2])) print('one each two: {}'.format(vowels[::2]))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# iteration # iteration
for vowel in vowels: for vowel in vowels:
print(vowel.upper()) print(vowel.upper())
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# enumeration # enumeration
for index, vowel in enumerate(vowels): for index, vowel in enumerate(vowels):
print("vowel {} is {}".format(1+index, vowel)) print("vowel {} is {}".format(1+index, vowel))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Immutable sequences #### Immutable sequences
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
vowels = ('a', 'e', 'i', 'o', 'u', 'y') vowels = ('a', 'e', 'i', 'o', 'u', 'y')
print(type(vowels)) print(type(vowels))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
vowels[1] = 'b' vowels[1] = 'b'
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Mutable sequences #### Mutable sequences
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
vowels = ['a', 'e', 'i', 'o', 'u', 'y'] vowels = ['a', 'e', 'i', 'o', 'u', 'y']
print(type(vowels)) print(type(vowels))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
vowels[1] = 'b' vowels[1] = 'b'
print(vowels) print(vowels)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Dictionaries #### Dictionaries
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# build using literal construct: {k1: v1, k2:v2} # build using literal construct: {k1: v1, k2:v2}
D = {"one": 1, D = {"one": 1,
"two": 2, "two": 2,
"three": 3} "three": 3}
print('D: {}'.format(D)) print('D: {}'.format(D))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# indexing # indexing
print(D["one"]) print(D["one"])
print(D["two"]) print(D["two"])
print(D["three"]) print(D["three"])
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# iterating # iterating
for item in D.items(): for item in D.items():
print(item) print(item)