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")
Q. Assign a value to a variable (references, most things are mutable)
In [134]:
name = "Nathan Faggian"
name
Out[134]:
In [135]:
yourname = name
id(name), id(yourname)
Out[135]:
Q. Mutate a string.
In [136]:
title = "Dr " + name
title
Out[136]:
Q. How do you form a container for information? Tuples.
In [137]:
container = ("Nathan", 182)
container
Out[137]:
Sets are also appropriate if you don't want order to be preserved.
In [138]:
container = set(["nathan", 182])
container
Out[138]:
In [139]:
182 in container
Out[139]:
Q. Sorting tabular datasets. Lists of Tuples and the sorted built-in.
In [140]:
table = [("Nathan", 182), ("Michael", 175), ("Sam", 190)]
table
Out[140]:
In [141]:
sorted(table)
Out[141]:
In [142]:
sorted(table, key=lambda x:x[1], reverse=True)
Out[142]:
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]:
In [144]:
heights["Michael"]
Out[144]:
Q. Who is the tallest person?
In [145]:
import operator
sorted(heights.items(), key=operator.itemgetter(0), reverse=True)
Out[145]:
In [146]:
year = 2015
In [147]:
year > 2020
Out[147]:
In [148]:
(year > 2010) and (year < 2020)
Out[148]:
In [149]:
(2010 < year < 2020)
Out[149]:
Basic example of selection:
if (condition):
operation
else
operation
Q. Is the year 2000 a, gregorian calendar, leap year?
Leap years:
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))
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]:
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))
Tip: Python allows you to use both functional and imperative styles and lets the user determine which approach is best.
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]:
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]:
For loops are also fine but more verbose:
In [158]:
total = 0
for x in data:
if x > 2:
total += x
total
Out[158]:
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]:
There are also dictionary comprehensions.
In [160]:
{k:v for k,v in [("a", 2), ("b",4)] if v > 2}
Out[160]:
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]: