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:
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')
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')
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)
In [ ]:
example_list = ['b', 'a', 'a', 1.0]
example_list
The example above illustrates a several points:
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)
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,
In [ ]:
example_dict = {'ccc': 1, 'b': 'hello world'}
example_dict
In [ ]:
example_dict['b']
The example above illustrates some key points:
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
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.
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__
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 |
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 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)
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) )
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))
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!