Robert Putnam Research Computing Services putnam@bu.edu
If you are on a Linux system that has python installed, type python at a command prompt to start things.
(Type exit() or quit()to end the session.)
[putnam@scc1 content]$ python Python 2.6.6 (r266:84292, Feb 22 2013, 00:00:18) [GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2 Type "credits", "demo" or "enthought" for more information. >>> quit()
Python is also available via your browser here(2.x) or here (2.x, ipython) or here(3.x).
>>> 7*9 63 >>> 1/2 + 10 10 >>> 1.0 /2 + 20/ 2.0 10.5
>>> x = "variables" >>> y = "are just names" >>> print x, y variables are just names >>> print "variables", y variables are just names >>> x+y 'variablesare just names' >>> z = "this is important later on" >>> x = 10 >>> y = 1.2 >>> print z, x, type(y) this is important later on 10 <type 'float'>
>>> x = 10 >>> y = 12 >>> x>y False >>> if x>y: ... bigger_one = x ... else: ... bigger_one = y ... >>> x>y False >>> not x>y True >>> bigger_one 12
C example
int x, y, bigger_one; x = 10; y = 12; if (x > y) { // first code block bigger_one = x; } else { // second code block bigger_one = y; }
indentation helps, no?
int x, y, bigger_one; x = 10; y = 12; if (x > y) { // first code block bigger_one = x; } else { // second code block bigger_one = y; }
Fortran ...
integer :: x, y, bigger_one x = 10 y = 12 if (x > y) then ! first code block bigger_one = x else ! second code block bigger_one = y end if
Matlab ...
x = 10; y = 12; if x > y % first code block bigger_one = x; else % second code block bigger_one = y; end
print "Indented code is easier to read" if True: print "You can tell that code is only executed sometimes" print "Python strives to be readable, so it mandates indentation" if True: print "A code block begins/ends when the indentation changes" print "blank lines are ignored (in scripts/files)" print "Interactively, blank lines mean the end of multi-lined code"
>>> print "Indented code is easier to read" Indented code is easier to read >>> if True: ... print "You can tell that code is only executed sometimes" ... print "Python strives to be readable, so it mandates indentation" ... if True: ... print "A code block begins/ends when the indentation changes" ... You can tell that code is only executed sometimes Python strives to be readable, so it mandates indentation A code block begins/ends when the indentation changes >>> print "blank lines are ignored (in scripts/files)" File "<console>", line 1 print "blank lines are ignored (in scripts/files)" ^ IndentationError: unexpected indent >>> print "Interactively, blank lines mean the end of multi-lined code" Interactively, blank lines mean the end of multi-lined code
>>> def add(x, y): ... result = x + y ... return result # can just be: return x+y ... >>> j = add(5, 7) # x = 5 and y = 7 >>> print j 12 >>> add(-1, 4) 3
Let's walk through this add function
>>> def bigger_one(x, y): ... "returns the value of the larger of two numbers" ... if x>y: ... return x ... elif y>x: ... return y ... return None # overkill: it's the default ... >>> bigger_one(10, 12) 12 >>> bigger_one(5, -3) 5 >>> bigger_one(4, 4) >>> print bigger_one(4, 4) None
You are given two values:
if it's a vacation, you always sleep in
if it's not a weekday, you sleep in too
also return True
Otherwise you don't sleep in
return False
def sleep_in(weekday, vacation): if vacation: return True if not weekday: return True return False
def sleep_in(weekday, vacation): if vacation or not weekday: return True return False
def sleep_in(weekday, vacation): return vacation or not weekday
So far...
You combine strings with +
you get name, which holds a string
you need to return 'Hello, name!',
where name is the value of name
def hello_name(name): return 'Hello ' + name + '!'
Single quotes
'Hello, everyone!'
are the same as double quotes
"Hello, everyone!"
Try Make Tags!
Look at the example nobel.py, and confirm your understanding of newlines, comments, and multi-line strings.
doc strings are unassigned strings at the beginning of block.
They are used as documentation.
>>> def add(x,y): ... "return sum of x and y" ... return x+y ... >>> help(add) Help on function add in module __main__: add(x, y) return sum of x and y
So far...
code blocks require indentation
if/else/elif with True and False
functions are defined using def
Strings are just text
'single' same as "double"
'''triple quote
can be multi-lined'''
+ add to concatenate
#: pound is comment character
remember variables are just names ...
>>> alist = [1, 2, 3] >>> alist [1, 2, 3] >>> [1, 2.0, '3'] [1, 2.0, '3']
Nth value | 1 | 2 | 3 | ... | N |
---|---|---|---|---|---|
forwards | 0 | 1 | 2 | ... | N-1 |
backwards | -N | -N+1 | -N+2 | ... | -1 |
>>> print alist[0], alist[1], alist[2] 1 2 3 >>> print "alist has", len(alist), "elements" alist has 3 elements >>> print alist[-1], alist[-2], alist[-3] 3 2 1 >>> alist[0] = 2
>>> x = [0, '1', 2.25] >>> y = [0, '1', 2.25] >>> z = x >>> z[0] = 99 >>> x[2] = 101
Let's walk through this.
Take a look at the practice problem found in dot_product1.py
First Last 6, another Codingbat.com example can be solved several ways.
That is, they are mutable
append is a method we can use to extend a list
>>> alist = [1, 2, 3] >>> alist.append(4) >>> alist [1, 2, 3, 4]
Concat...
>>> thelist = alist + [5, 7] >>> thelist [1, 2, 3, 4, 5, 7]
Insert...
>>> thelist.insert(5, 6) # index 5 is 6th position >>> print thelist [1, 2, 3, 4, 5, 6, 7]
Delete...
>>> del thelist[5] >>> thelist [1, 2, 3, 4, 5, 7]
in is a keyword used to check if an element is in a list:
>>> thelist [1, 2, 3, 4, 5, 7] >>> 1 in thelist True >>> '1' in thelist False
Python loves to use list-like behavior over and over again
Strings act like lists:
>>> name = "Tommy" >>> name[0:3] # make a "slice" from indices 0 through 2 'Tom' >>> len(name) 5
But strings are immutable--you can't edit them:
>>> name[1] = 'a' Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: 'str' object does not support item assignment
>>> #this is >>> a = ['cat', 'window', 'defenestrate'] >>> for x in a: ... print x, len(x) ... cat 3 window 6 defenestrate 12 >>> #the same as
>>> x = a[0] >>> print x, len(x) cat 3 >>> x = a[1] >>> print x, len(x) window 6 >>> x = a[2] >>> print x, len(x) defenestrate 12
See if you can count how many even numbers exist in a list.
% is the modulus (remainder) operator.
>>> 7%2 # 7 is odd, so remainder of 1 1 >>> 8%2 # 8 is even, so remainder of 0 0
Use this on each element to see if they are even or odd.
Note: We don't care about each element's index
Loops in C involving incrementing a counter
int x; for (x=0; x<10; x++) { // Stuff }
range() is a method that makes a list, from 0 to N-1
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(5, 10) [5, 6, 7, 8, 9] >>> range(0, 10, 3) [0, 3, 6, 9]
>>> for i in range(len(a)): ... print i, a[i] ... 0 cat 1 window 2 defenestrate >>> # required blank line...
Use this newfound knowledge on dot_product2.py
The solution is found here: practice/solutions/dot_product2.py
1 # try to complete the function dot_product: 2 # also read through the other functions in this code and try 3 # to understand what they do 4 5 def dot_product(length, vec1, vec2): 6 """Returns the dot product of two vectors 7 8 `vec1` and `vec2` are each `length` elements long 9 """ 10 product = 0 11 for i in range(length): 12 product += vec1[i] * vec2[i] 13 return product
while repeats until something is False
"while something is True, keep doing code-block"
>>> x=0 >>> while x<4: ... x += 1 ... print x ... 1 2 3 4 >>>
break is a way to get out of any loop:
>>> nums = [7, 1, 13, 4] >>> x=0 >>> while True: ... if nums[x] > 10: ... break ... else: ... print x, nums[x] ... x+=1 ... 0 7 1 1 >>>
So far...
These are like flexible lists.
Here we're making a telephone book..
>>> tel = {'jack':4098, 'sape':4139} >>> tel {'sape': 4139, 'jack': 4098} >>> type(tel) <type 'dict'>
curly braces are used for construction
But you still access with [ and ]:
>>> tel['jack'] 4098
Assignment can change a key's value,
or it can add a new key:value pair:
>>> tel['guido'] = 4127 >>> tel {'sape': 4139, 'jack': 4098, 'guido': 4127} >>> tel['sape'] = 4039 >>> tel {'sape': 4039, 'jack': 4098, 'guido': 4127}
Let's visualize this!
keys() returns a list of all the 'keys'
>>> names = tel.keys() >>> names ['sape', 'jack', 'guido'] >>> for person in names: ... print person+"'s number is", tel[person] ... sape's number is 4039 jack's number is 4098 guido's number is 4127 >>> # extra return
In practice you would just do this
>>> names = tel.keys() >>> names ['sape', 'jack', 'guido'] >>> for person in tel: ... print person+"'s number is", tel[person] ... sape's number is 4039 jack's number is 4098 guido's number is 4127 >>> # extra return
values() gives you a list of the values
>>> tel.values() [4039, 4098, 4127] >>> max(tel.values()) 4127
A list that cannot change (i.e., is "immutable").
Use comma(s) to construct.
>>> def diff_sum(x, y): ... return x-y, x+y ... >>> diff_sum(1, 2) (-1, 3) >>> t = diff_sum(1, 2) >>> print t[0] -1 >>> print t[1] 3 >>> x, y = diff_sum(1, 2) >>> print x, y -1 3 >>> (x, y) = diff_sum(1, 2) >>> print x, y -1 3
Any file read (and executed) by python like so:
python somefile.py
Any file read (and executed) by python from another file:
>>> import random >>> random <module 'random' from '/usr/lib64/python2.6/random.pyc'>
help(random)
Help on module random: NAME random - Random variable generators. FILE /usr/lib64/python2.6/random.py DESCRIPTION integers -------- uniform within range sequences --------- pick random element pick random sample generate random permutation distributions on the real line: ------------------------------ uniform triangular normal (Gaussian) lognormal negative exponential gamma beta pareto Weibull distributions on the circle (angles 0 to 2pi) --------------------------------------------- circular uniform von Mises
random is a module that comes with Python,
but it's not loaded by default
We'll focus on two functions that random defines
>>> random.randint(0, 9) 2 >>> random.randint(0, 9) 9 >>> random.randint(0, 9) 6 >>> random.randint(0, 9) 2
>>> lucky = ['Tim', 'Tom', 'Ted', 'Tony'] >>> type(lucky) <type 'list'> >>> random.choice(lucky) 'Tom' >>> random.choice(lucky) 'Tony' >>> random.choice(lucky) 'Ted' >>> random.choice(lucky) 'Tom' >>> random.choice(lucky) 'Tom' >>> random.choice(lucky) 'Tony' >>> random.choice(lucky) 'Tony'
Put it all together with state_capitals.py
Today ...