Software Carpentry Bootcamp
Columbia University, NYC,
January 2013
Uploaded and Presented by: Adina Howe
Based on material prepared by: Matt Davis, Katy Huff, Justin Kitzes, and Tracy Teal
The most basic component of any programming language are "things", also called variables or (in special cases) objects.
The most common basic "things" in Python are integers, floats, strings, booleans, and some special objects of various types. We'll meet many of these as we go through the lesson.
TIP: To run the code in a cell quickly, press Ctrl-Enter.
TIP: To quickly create a new cell below an existing one, type Ctrl-m then b. Other shortcuts for making, deleting, and moving cells are in the menubar on the left of the screen. To hide the menubar, click on the vertical gray divider separating it from this main page.
# A thing
2
2
# Use print to show multiple things in the same cell
# Note that you can use single or double quotes for strings
print 2
print 'hello'
2 hello
# Things can be stored as variables
a = 2
b = 'hello'
c = True # This is case sensitive
print a, b, c
2 hello True
# The type function tells us the type of thing we have
print type(a)
print type(b)
print type(c)
<type 'int'> <type 'str'> <type 'bool'>
Just storing data in variables isn't much use to us. Right away, we'd like to start performing operations and manipulations on data and variables.
There are three very common means of performing an operation on a thing.
All of the basic math operators work like you think they should for numbers. They can also
do some useful operations on other things, like strings. There are also boolean operators that
compare quantities and give back a bool
variable as a result.
# Standard math operators work as expected on numbers
a = 2
b = 3
print a + b
print a * b
print a ** b
5 6 8
# Except for division
print 2 / 3
print 2 / 3.
0 0.666666666667
# There are also operators for strings
print 'hello' + 'world'
print 'hello' * 3
# print hello / 3
helloworld hellohellohello
# Boolean operators compare two things
a = (1 > 3)
b = (3 == 3)
print a
print b
print a & b
False True False
a = 5
b = 2
a + b
#print a + b
7
c = b
b = 95 # changing b doesn't change c
a + c
7
d = (a + b) * c # doesn't print anything
print a, b, c
print d
5 95 2 200
These will be very familiar to anyone who has programmed in any language, and work like you would expect.
# There are thousands of functions that operate on things
print type(3)
print len('hello')
print round(3.3)
<type 'int'> 5 3.0
TIP: To find out what a function does, you can type it's name and then a question mark to get a pop up help window. Or, to see what arguments it takes, you can type its name, an open parenthesis, and hit tab.
#round?
#round(
round(3.14159, 2)
3.14
TIP: Many useful functions are not in the Python built in library, but are in external scientific packages. These need to be imported into your Python notebook (or program) before they can be used. Probably the most important of these are numpy and matplotlib.
# Many useful functions are in external packages
# Let's meet numpy
import numpy as np
# To see what's in a package, type the name, a period, then hit tab
#np?
#np.
# Some examples of numpy functions and "things"
print np.sqrt(4)
print np.pi # Not a function, just a variable
print np.sin(np.pi)
2.0 3.14159265359 1.22464679915e-16
In the simplest terms, you can think of an object as a small bundled "thing" that contains within itself both data and functions that operate on that data. For example, strings in Python are objects that contain a set of characters and also various functions that operate on the set of characters. When bundled in an object, these functions are called "methods".
A function is a piece of code that is called by name. It takes data as an input to perform operations on (in other words, it is passed data explicitly). A method is a piece of code that is called by name that is associated with an object. It is very similar to a function and is passed data implicitly.
# A string object
a = 'hello, world'
print type(a)
<type 'str'>
# String objects have bundled methods
#a.
#a.count?
print a.capitalize()
print a.replace('l', 'X')
Hello, world heXXo, worXd
A discrete time equation for logistic population growth is shown below. For the specific population of study, cats at my uncle's house, the constants are given.
N1 = N0 + r * N0 * [1 - N0 / K]
where n(t) is the population size at time t, r is the growth rate, and K is the carrying capacity of the home.
Given: r is 0.6, K is 100, and N0 is 10.
Write Python expressions that do the following:
r
, K
, and n0
, setting these equal to their given values.n1
and calculate it's value. Do the same for n2
.n2
- what is it?n2
is larger than 20, and print out a line that says "n2 more than 20: "followed by the answer.
n2
is an integer, and print out a line that says "n2 is int: " followedby the answer (HINT: look at the methods of n2
.)
n1
and n2
so that these values are rounded to the nearestinteger.
r = 0.6
K = 100.
n0 = 10.
n1 = n0 + r*n0*(1 - n0/K)
n2 = n1 + r*n1*(1 - n1/K)
print n0, n1, n2
print type(n2)
print 'n2 more than 20: ', n2 > 20
print 'n2 is int: ', n2.is_integer()
10.0 15.4 23.21704 <type 'float'> n2 more than 20: True n2 is int: False
Once the number of variables that you are interested in starts getting large, working with them all individually starts to get unwieldy. To help stay organized, we can use collections of things.
Probably 99% of your work in scientific Python will use one of four types of collections: lists, tuples, dictionaries, and numpy arrays. We'll look quickly at each of these and what they can do for you.
Lists are probably the handiest and most flexible type of container. Lists are declared with
square brackets []. Individual elements of a list can be selected using the syntax a[ind]
.
# Lists are created with square bracket syntax
a = ['hi', 'hello', 'yo']
print a, type(a)
['hi', 'hello', 'yo'] <type 'list'>
# Lists (and all collections) are also indexed with square brackets
# NOTE: The first index is zero, not one
print a[0]
print a[1]
hi hello
# Lists can be sliced by putting a colon between indexes
# NOTE: The end value is not inclusive
print a[0:2]
['hi', 'hello']
# You can leave off the start or end if desired
print a[:2]
print a[2:]
print a[:]
print a[:-1]
['hi', 'hello'] ['yo'] ['hi', 'hello', 'yo'] ['hi', 'hello']
# Lists are objects, like everything else, and have methods such as append
a.append('hiya')
print a
a.append([1,2])
print a
#Functions can also be applied to lists.
print len(a)
['hi', 'hello', 'yo', 'hiya', [1, 2], 'hiya'] ['hi', 'hello', 'yo', 'hiya', [1, 2], 'hiya', [1, 2]] 7
Make a list with 5 things in it. Print the 4th thing in the list. Print the sublist containing the 3rd, 4th, and 5th things in the list.
We won't say a whole lot about tuples except to mention that they basically work just like lists, with two major exceptions:
t = ('zero', 1, 2.0)
t
('zero', 1, 2.0)
t[0] = 99
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) /Users/adina/Documents/swc/boot-camps/1-Python/notebooks/prepared-demos/<ipython-input-21-e77c201e67de> in <module>() ----> 1 t[0] = 99 TypeError: 'tuple' object does not support item assignment
A dictionary is a unordered collection of key/value pairs. Dictionary keys are immutable, unique,and not stored in any order. There are no restrictions on values stored in dictionaries.
d = {'first': 'alpha', 'two': 2, 2: 'two'}
print d
print d['first'], d[2]
{2: 'two', 'two': 2, 'first': 'alpha'} alpha two
d['first'] = 'uno'
print d['first']
uno
d['last'] = 'omega'
print d['last']
d[3.14159] = 'pi'
print d[3.14159]
omega pi
print len(d), d
5 {3.14159: 'pi', 2: 'two', 'last': 'omega', 'two': 2, 'first': 'uno'}
< > <= >= == !=
x = 5
if x < 0:
print "x is negative"
x = -5
if x < 0:
print "x is negative"
x is negative
x = 5
if x < 0:
print "x is negative"
else:
print "x in non-negative"
x in non-negative
x = 5
if x < 0:
print "x is negative"
elif x == 0:
print "x is zero"
else:
print "x is positive"
x is positive
fruits = ['apples', 'oranges', 'pears', 'bananas']
i = 0
while i < len(fruits):
print fruits[i]
i = i + 1
apples oranges pears bananas
for fruit in fruits:
print fruit
apples oranges pears bananas
# Use range for a range on integers
for i in range(len(fruits)):
print i, fruits[i]
0 apples 1 oranges 2 pears 3 bananas
# Use zip to iterate over two lists at once
fruits = ['apples', 'oranges', 'pears', 'bananas']
prices = [0.49, 0.99, 1.49, 0.32]
for fruit, price in zip(fruits, prices):
print fruit, "cost", price, "each"
apples cost 0.49 each oranges cost 0.99 each pears cost 1.49 each bananas cost 0.32 each
# Use "items" to iterate over a dictionary
# Note the order is non-deterministic
prices = {'apples': 0.49, 'oranges': 0.99, 'pears': 1.49, 'bananas': 0.32}
for fruit, price in prices.items():
print fruit, "cost", price, "each"
pears cost 1.49 each apples cost 0.49 each oranges cost 0.99 each bananas cost 0.32 each
# Calculating a sum
sum = 0
values = [1,2,3,4]
for x in values:
sum = sum + x
sum
10
product = 1
for x in range(1, 42 + 1):
product = product * x
print '%.4e' % product
1.4050e+51