Basic training in Python

Python is a flexible programming language that is becoming increasingly popular for scientific computing. This session will give you a basic foundation in how to work effectively with Python.

During the session you will learn:

  • How to work interactively with Python
  • How to make use of Python’s built-in data structures

During this part of the course we will illustrate how to work interactively with Python using IPython notebook.

Let us start by reproducing the famous "hello world" program.

As you work through this notebook you will need to press Shift-Enter to run the code.


In [ ]:
print("hello world")

Unlike Bash, Perl and PHP single and double quotes are equivalent. I.e. the previous “hello world” example could just as well have been written as:


In [ ]:
print('hello world')

Data types

Python has a number of built in data types. These are used to represent things such as integers, floating point numbers and text strings. To find out what the type of something is one can use the type keyword.


In [ ]:
type(7)

In [ ]:
type(7.)

It is worth noting that, in Python 2, dividing two integers with each other results in integer division, i.e. division with the fractional part discarded.


In [ ]:
3 / 2

If either the numerator or denominator is a float the result of the division will be returned as a floating point number.


In [ ]:
3 / 2.

In Python 3 dividing two integers will return a floating point number. If you really want integer division and want to future proof your code you can use the integer division operator //.


In [ ]:
3 // 2

Text is represented as a string (str). This is true both for individual characters as well as longer pieces of text.


In [ ]:
type('h')

In [ ]:
type('hello world')

In Python 3 the default text representation is Unicode.

To get a Unicode string in Python 2 one can prefix it with a u.


In [ ]:
type(u'hello world')

Variables

It is easy to assign a variable in Python.


In [ ]:
a = 100
b = 10
c = a * b
print(c)

Variables are not statically typed in Python. This means that it is possible to change a variable to a different type.


In [ ]:
type(a)

In [ ]:
a = 'hello world'
type(a)

Data structures

Python has got several built-in data structures. Two of the most useful ones are lists and dictionaries.

Lists

Let us have a look at lists first.


In [ ]:
example_list = ['b', 'a', 'a', 1.0]
example_list

The example above illustrates a several points:

  • a list can be created by placing a number of comma separated objects in square brackets
  • the elements of a list do not need to be unique (there are two instances of the string ‘a’)
  • the elements of a list can have differing type (the list contains both strings and a floating point number)

Lists have order. This means that we can access elements from the list using indices. The indices in Python are zero based, i.e. the first element in the list has got index zero.


In [ ]:
example_list[0]

Note that we can change the elements of a list.


In [ ]:
example_list[0] = 'hello'
example_list

It is possible to get the last element of the list using the index -1.


In [ ]:
example_list[-1]

Another common task is to find out the length of a list. This can be achieved using the len() function.


In [ ]:
len(example_list)

Tuples

A tuple is an ordered collection of elements. It is different from a list in that it cannot be modified once created.

Let us illustrate this with an example.


In [ ]:
example_tuple = ('b','a', 'a', 1.0)
example_tuple

In [ ]:
example_tuple[0]

In [ ]:
example_tuple[0] = 'hello'

It is easy to inadvertently create tuples as they are created by default when one separates objects by commas.


In [ ]:
1, 2, 3

In [ ]:
4,

Dictionaries

A Python dictionary is a set of key value pairs. In other languages these are often referred to as maps or hashes.


In [ ]:
example_dict = {'ccc': 1, 'b': 'hello world'}
example_dict

In [ ]:
example_dict['b']

The example above illustrates some key points:

  • one can create a dictionary by providing a set of comma separated key:value pairs in {curly braces}
  • a dictionary does not have any inherent order
  • one can access a value by its key

The keys in a dictionary are unique, i.e. if one tries to add another element to the dictionary with a key that already exists the value of the existing element for that key will be replaced with the new one.


In [ ]:
example_dict['b'] = 2
example_dict

Whitespace matters!

In Python whitespace characters have meaning. Code which is indented to the same level represents a code block. Functions, if statements and loops are all examples of code blocks. In programming languages such as C and Perl code blocks are denoted using {curly braces}.


In [ ]:
if True:
    print('hello')
    print('world')

If your code is not correctly aligned you will see IndentationError messages telling you that everything is not as it should be. You will also run into IndentationError messages if you mix white spaces and tabs.


In [ ]:
if True:
    print('hello')
   print('world')

The Python standard is to use four white spaces to indent code.

This may sound really annoying. However there is good reason for it in that it improves the readability of the code.

Functions

Functions can be used to create re-usable pieces of code and are useful for breaking up code into smaller more manageable pieces.

To create a function in Python we use the def keyword. The code snipped below defines a function named hello.


In [ ]:
def hello():
    print('hello world')

hello

To call the hello function we need a parenthesis at the end.


In [ ]:
hello()

Let us improve the hello function to take a name as an input argument.


In [ ]:
def hello(name):
    print('hello ' + name)
    
hello('pat')

Finally let us document the function.


In [ ]:
def hello(name):
    "Returns a personal greeting as a string."
    print('hello ' + name)
    
hello('jess')

In [ ]:
hello.__doc__

Conditional statements and boolean operators

The conditional statement keywords in Python are if, elif and else. Below is a simple, albeit boring, example.


In [ ]:
if False:
    print("you won't see this printed")
if True:
    print("hello")

Let us write a function to illustrate a slightly more realistic usage.


In [ ]:
def net_salary(gross_salary):
    "Returns the net salary by deducting tax from the gross."
    if gross_salary < 10000:
        return gross_salary * 1.0
    elif gross_salary < 32000:
        return gross_salary * 0.8
    else:
        return gross_salary * 0.6

In [ ]:
net_salary(9000)

In [ ]:
net_salary(31000)

In [ ]:
net_salary(33000)

In python the keyword for the “else if” conditional is elif, this is often a source of confusion for people who are used to other languages.

In the example above we make use of the < (less than) boolean operator. Other useful boolean operators include:

Operator Description
== Equal
!= Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal

Looping

In scripting and programming one often needs to loop over a series of elements. These could be a series of numbers, list items or lines from a file.

The for loop construct

The most commonly used loop structure in Python is the for loop. Let us illustrate this by iterating over the items in a list.


In [ ]:
for item in ['hello', 'world']:
    print(item)

The range function

To loop over the values one to ten one can make use of Python’s built-in range function. By default this generates zero-based arithmetic progressions.


In [ ]:
range(10)

However, we can tell it to start at one.


In [ ]:
range(1, 10)

Finally, we extend the range to include the value 10.


In [ ]:
range(1, 11)

It is worth noting that we can alter the step size so it is, for example, possible to generate a list counting down in steps of 2 from 10 to 0.


In [ ]:
range(10, 0, -2)

Suppose that we wanted to know what the sum of these values were. We could achieve that using a for loop.


In [ ]:
total = 0
for value in range(10, 0, -2):
    total = total + value

total

Alternatively, we could have used Python’s built-in sum() function.


In [ ]:
sum( range(10, 0, -2) )

The enumerate function

One often wants to know how far through a loop one is and it is quite common to see code along the lines of the below.


In [ ]:
count = 0
for word in ['hello', 'my', 'name', 'is', 'pat']:
    print("{} {}".format(count, word))
    count = count + 1

However, a there is a neater solution to this problem. One can make use of the enumerate()function.


In [ ]:
for count, word in enumerate(['hello', 'my', 'name', 'is', 'pat']):
    print("{} {}".format(count, word))

Let's get some practice

This introduction has gone through the first half of the material in the Introduction to Python Course.

Each section of the course has a set of exercises associated with it.

If you are completely new to Python, go to the course book and complete these exercises.

If you were already familiar with the material outlined in this introduction skip to the section on working with files.

Enjoy!