Introduction to Python



Robert Putnam
Research Computing Services
putnam@bu.edu

Objectives

  • Introduce Python
  • Introduce programming concepts
  • Leave no student behind (translation: ask questions!)

Outline

  • variables
  • functions
  • if/else
  • lists
  • loops
  • dictionaries
  • modules

Pythonic web sites

Python is ...

  1. interactive
  2. extensible
  3. portable
  4. changing and evolving (2.x -> 3.x)
  5. ubiquitous (scripting, web programming, plugins, etc.)
  6. created by Guido van Rossum, a fan of Monty Python's Flying Circus
  7. possibly a cult

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
Enthought Python Distribution -- www.enthought.com
Version: 7.3-2 (64-bit)

Python 2.7.3 |EPD 7.3-2 (64-bit)| (default, Apr 11 2012, 17:52:16)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "credits", "demo" or "enthought" for more information.
>>> quit()

Python is also available via your browser here.

>>> 7*9
63
>>> 1/2 + 10
10
>>> 1.0 /2 + 20/ 2.0
10.5
  • The >>> is the prompt, asking for code.
  • Up/down arrows give access to command/code history
  • We can use python as a calculator, using these math operators:
    • + addition
    • - subtraction
    • * multiplication
    • / division different in 3.x!
    • // floor division
    • % modulus (remainder)
    • ** exponent
  • Other operators

We can save values in variables by using the "=" sign. This is variously called "assigning a variable" or "binding" a name to an object.

>>> 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'>



Some fine print about 2.x -> 3.x
More fine print about 2.x -> 3.x

Code Blocks

Example 1:

if/else

>>> 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

Example 2:

functions

>>> 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

Codingbat.com

  1. In the text box, you write your function.
  2. Press GO to test your work.
  3. See if you passed the tests on the right.

Sleep In

  1. You are given two values:

    1. vacation - is it a vacation day?
    2. weekday - is it a weekday?
  2. if it's a vacation, you always sleep in

  3. if it's not a weekday, you sleep in too

    also return True

  4. 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...

  1. code blocks require indentation
  2. if/else/elif
    1. True, False are Boolean constants
  3. functions are defined using def
    1. return at any point
    2. None is the default return value

Strings

Hello Name

You combine strings with +

  1. you get name, which holds a string

  2. 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...

  1. code blocks require indentation

  2. if/else/elif with True and False

  3. functions are defined using def

  4. Strings are just text

    1. 'single' same as "double"

    2. '''triple quote

      can be multi-lined'''

    3. + add to concatenate

  5. #: pound is comment character

Lists

remember variables are just names ...

>>> alist = [1, 2, 3]
>>> alist
[1, 2, 3]
>>> [1, 2.0, '3']
[1, 2.0, '3']
  1. Square brackets are used for construction.

list indices

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.

Lists can change

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

Lists are big deal!

  • 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
    

(for) Loops

>>> #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

Count Evens

See if you can count how many even numbers exist in a list.

Count Evens

% 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

by counting

  • 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

Loops

forever

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...

  1. code blocks, if/else/elif/, functions, True, False
  2. Strings ...
  3. lists (variables are just names)
    1. index forward (0..N-1) and backward (-N..-1)
    2. they can change append, etc.
  4. loops
    1. for
    2. range
    3. while

Dictionaries

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

Tuples

A list that cannot change (i.e., is "immutable").

Use ( ) to construct, or not ....

>>> 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

Scripts

Any file read (and executed) by python like so:

python somefile.py

Modules

Any file read (and executed) by python from another file:

>>> import random
>>> random
<module 'random' from '/usr/local/apps/epd-7.3-2/lib/python2.7/random.pyc'>
help(random)
  Help on module random:

NAME
    random - Random variable generators.

FILE
    /usr/local/apps/epd-7.3-2/lib/python2.7/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

  • random is a module that comes with Python,

    but it's not loaded by default

  • We'll focus on two functions that random defines

    1. random.randint(a, b) -- pick a number between a and b (inclusive)
    2. random.choice(alist) -- give me a random element
>>> 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 ...

  1. code blocks, if/else/elif/, functions, True, False
  2. Strings ...
  3. lists, growing list of variable names
  4. loops: for, range, while
  5. dictionaries: a list of key:value pairs
  6. modules

Other Tutorials

The END