Introduction to Python

For Programmers

Yann Tambouret

Hi, I'm Yann

  • Scientific Programmer for SCV
  • You can reach me by email: yannpaul@bu.edu
  • We can help with C, C++, Python, Fortran, Perl, Matlab, R, Powerpoint, Parallel Programming ... etc.: help@scv.bu.edu

Objectives

  • Introduce Python 2.X
  • Cover the basic hurdels
  • Set you up for self-training

Outline

  • Variables - are just names
  • functions
  • if-statements
  • lists
  • loops
  • dictionaries
  • modules

Survey

Thanks to Boston Python

Python is ...

  1. interpretive
  2. a language that is changing (a bit)
  3. used for everything

In the browser --or--

In the console, type python to start things.

Type exit() to end the session:

[yannpaul@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.
>>> exit()

This is fine for quick coding sessions, but nothing's saved.

>>> 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
>>> x = "variables"
>>> y = "are just names"
>>> print x, 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'>

Code Blocks

From wikipedia:

a section of code which is grouped together.

Example 1:

if/else

First Python ...

>>> x = 10
>>> y = 12
>>> x>y
False
>>> if x>y:
...    print "x is bigger!"
...    bigger_one = x
... else:
...    print "y is bigger!"
...    bigger_one = y
... 
y is bigger!
>>> x>y
False
>>> not x>y
True
>>> print bigger_one
12

Now C ...

  • Python is ... interperative.

  • C programming is not

    file -> compier -> executable

C example

int x, y, bigger_one;
x = 10;
y = 12;
if (x > y) {
// first code block
bigger_one = x;
}
else {
// second code blocks
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 blocks
    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

Odd detail: interactive python requires blank indentation.

In scripts (more later), python ignores blank lines

>>> if True:
...     x = 10
... 
>>>     y = x * 2
  File "<console>", line 1
    y = x * 2
   ^
IndentationError: unexpected indent

Example 2:

functions

>>> def add(x, y):
...     return x + y
... 
>>> result = add(5, 7) # x = 5 and y = 7
>>> print result
12
>>> add(-1, 4)
3
>>> 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. Write your function.
  2. Press GO
  3. See if you passed

First, not, True, and False

>>> not False
True
>>> not True
False
>>> if not False:
...     print "... then it must be true"
... 
... then it must be true
>>> # another blank line

Sleep In

  1. You are given two values:
    1. weekday - is it a weekday? (True or False value)
    2. vacation - is it a vacation day? (True or False value)
  1. if it's a vacation, you always sleep in

    return True (True, you should sleep in)

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

    also return True

  1. Otherwise you don't sleep in

    return False

Example Use:

>>> x = sleep_in(True, True) # weekday = True, vacation = True
>>> print x
True

Example Answer:

def sleep_in(weekday, vacation):
    return True # always sleep in

And Now

Actual Answer

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

Errors

A Traceback is an error report:

yannpaul@scc1 examples]$ python traceback_example.py
Traceback (most recent call last):
  File "traceback_example.py", line 4, in <module>
    bad_function()
  File ".../examples/bad_module.py", line 5, in bad_function
    raise RuntimeError
RuntimeError

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, Yann!'

are the same as double quotes

"Hello, Yann!"

Homework: 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. '''trip 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

Homework: First Last 6

Lists can change

That is, they are mutable

append is the method used to extend a list

>>> alist[0] = 1
>>> alist.append(4)
>>> alist
[1, 2, 3, 4]
  • It's used in an object oriented fashion:

    • object.method() means:

      call function 'method' with first argument as 'object'

  • This also means method belongs to object.

    This comes up later when we talk about modules.

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]
    '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
>>> # blank line

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

Homework: Count Evens

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 new found 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 is a keyword for repeating 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
>>> #... extra blank line

break is a way to get out of any loop:

>>> x=0
>>> while True:
...     if x >= 4:
...           break
...     x += 1
...     print x
... 
1
2
3
4
>>> #... extra blank line

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!

  • The keys() method is a function that belongs to dictionaries.
  • It's used in an object oriented fashion:
    • object.method() means
    • call function 'method' with first argument as 'object'

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

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
    2. random.choice(alist) -- give me a random element
>>> help(random.randint)
Help on method randint in module random:

randint(self, a, b) method of random.Random instance
    Return random integer in range [a, b], including both end points.

>>> random.randint(0, 9)
6
>>> random.randint(0, 9)
4
>>> 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)
'Tony'
>>> random.choice(lucky)
'Tony'
>>> random.choice(lucky)
'Tim'
>>> random.choice(lucky)
'Tom'
>>> random.choice(lucky)
'Ted'

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

Survey