Welcome to the interactive Python session.

This notebook series is intended as a very high-level introduction to python and tools, for a more comprehensive set of material refer to the following reference:

https://wiki.python.org/moin/BeginnersGuide/Programmers

Also, consider working through the notes provided by Robert Johansson:

https://github.com/jrjohansson/scientific-python-lectures


Q. Print hello world to the screen:


In [133]:
print("Hello World")


Hello World

Q. Assign a value to a variable (references, most things are mutable)


In [134]:
name = "Nathan Faggian"
name


Out[134]:
'Nathan Faggian'

In [135]:
yourname = name

id(name), id(yourname)


Out[135]:
(88374512, 88374512)

Q. Mutate a string.


In [136]:
title = "Dr " + name
title


Out[136]:
'Dr Nathan Faggian'

Some core data types: Tuples, Lists, Dictionaries and Sets.

Q. How do you form a container for information? Tuples.


In [137]:
container = ("Nathan", 182)
container


Out[137]:
('Nathan', 182)

Sets are also appropriate if you don't want order to be preserved.


In [138]:
container = set(["nathan", 182])
container


Out[138]:
{'nathan', 182}

In [139]:
182 in container


Out[139]:
True

Q. Sorting tabular datasets. Lists of Tuples and the sorted built-in.


In [140]:
table = [("Nathan", 182), ("Michael", 175), ("Sam", 190)]
table


Out[140]:
[('Nathan', 182), ('Michael', 175), ('Sam', 190)]

In [141]:
sorted(table)


Out[141]:
[('Michael', 175), ('Nathan', 182), ('Sam', 190)]

In [142]:
sorted(table, key=lambda x:x[1], reverse=True)


Out[142]:
[('Sam', 190), ('Nathan', 182), ('Michael', 175)]

Q. How do you describe a relationship or a mapping of data? You can use lists of tuples but dictionaries are better.


In [143]:
heights = {"Nathan": 182, "Michael": 175, "Sam": 190}
heights


Out[143]:
{'Michael': 175, 'Nathan': 182, 'Sam': 190}

In [144]:
heights["Michael"]


Out[144]:
175

Q. Who is the tallest person?


In [145]:
import operator

sorted(heights.items(), key=operator.itemgetter(0), reverse=True)


Out[145]:
[('Sam', 190), ('Nathan', 182), ('Michael', 175)]

Basic boolean expressions, selection and iteration.


In [146]:
year = 2015

In [147]:
year > 2020


Out[147]:
False

In [148]:
(year > 2010) and (year < 2020)


Out[148]:
True

In [149]:
(2010 < year < 2020)


Out[149]:
True

Basic example of selection:

if (condition):
    operation
else
    operation

Q. Is the year 2000 a, gregorian calendar, leap year?

Leap years:

  • The year is evenly divisible by 4
  • If the year can be evenly divided by 100, it is NOT a leap year, unless the year is also evenly divisible by 400.

In [150]:
def is_leap_year(year):
    """
    Returns if the year is a leap year.
    """
    if year % 100 == 0:
        return year % 400 == 0
    else:
        return year % 4 == 0

Basic example of iteration:

for data in iterable:
    operation


In [151]:
years = [2010, 2011, 2016, 2020]
for year in years:
    if is_leap_year(year):
        print("{} is a leap year!".format(year))


2016 is a leap year!
2020 is a leap year!

Functions and Classes

Q. Write a greeting function that takes two arguments and returns a string.


In [152]:
def greet(first_name, last_name):
    """Returns a string"""
    return "Hello {} {}.".format(first_name, last_name)

In [153]:
greet("Nathan","Faggian")


Out[153]:
'Hello Nathan Faggian.'

Q. Write a basic class that encapsulates some data.


In [154]:
class Wallet(object):
    """
    A Wallet contains integers of dollars and cents.
    """
    
    def __init__(self, dollars, cents):
        self.dollars = dollars
        self.cents = cents
        
    def __repr__(self):
        return "Wallet({},{})".format(self.dollars, self.cents)
    
    def __del__(self):
        pass
    
pouch = Wallet(1000,0)
print("A wallet: {}, with {} dollars and {} cents.".format(pouch, 
                                                           pouch.dollars, 
                                                           pouch.cents))


A wallet: Wallet(1000,0), with 1000 dollars and 0 cents.

Tip: Python allows you to use both functional and imperative styles and lets the user determine which approach is best.

What makes Python different from other languages?


In [155]:
import this

Q. Form an array of values and sum then together using the sum built-in.


In [156]:
data = [1, 2, 3, 4]
sum(data)


Out[156]:
10

For simple things the R language looks similar, especially math.

data <- c(1,2,3,4)
sum(data)

Q. Sum an array of values only if the values are greater than 2.


In [157]:
sum([x for x in data if x > 2])


Out[157]:
7

For loops are also fine but more verbose:


In [158]:
total = 0
for x in data:
    if x > 2:
        total += x 
total


Out[158]:
7

Influences from functional programming make code easier to read and understand - list comprehensions.


In [159]:
[x for x in data if x > 2]


Out[159]:
[3, 4]

There are also dictionary comprehensions.


In [160]:
{k:v for k,v in [("a", 2), ("b",4)] if v > 2}


Out[160]:
{'b': 4}

Context managers, can take care of handling the opening and closing of files.


In [161]:
with open('test.file', 'w') as file_handle:
    file_handle.write("Hello")

Q. An infinite fibonacci sequence. A. Using generators.


In [162]:
def fib():
   a, b = 0, 1
   while True:
      yield b
      a, b = b, a + b

In [163]:
fib_generator = fib()

In [164]:
value = next(fib_generator)
value


Out[164]:
1