Introduction to Python for Scientific Computing - Tutorial n°1

Mohammed Ait Lahcen, Economic Theory Group, Faculty of Business and Economics, University of Basel

This series of tutorials offers an introduction to Python for scientific computing. In this first tutorial we take a look at some of the basics of the core language.

For a more detailed introduction to Python for scientific computing you are encouraged to refer to the lectures available at QuantEcon.org.

Data types

Common data types in Python include:

  • String
  • Integer
  • Float
  • Boolean
  • ...

The ones we will usually encounter in scientific programming are numbers (integers, floats,...).

Python also offers data types for storing collections of objects. These are called container types and include:

  • Lists
  • Tuples
  • Dictionaries
  • ...

We will have a look at container types a bit later.

Non-native Python data types can be added by importing additionnal packages (e.g. array, dataframe, series, etc).

Variable assignment

You can create a variable just by assigning a value to it. The assignment operator in Python is =

In [1]:
x = 1
In [2]:
x
Out[2]:
1

As opposed to languages such as C, Java and Fortran, Python is a dynamically typed language. This means that we do not need to specify the type of a variable when we create one. Python takes care of that by infering the type of the variable from the value that was assigned to it. This is very convenient in use but might slow down the code's performance during execution relative to static languages.

In [3]:
type(x)
Out[3]:
int

If you try to use a variable that has not yet been defined you will get a NameError:

In [4]:
type(y)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-4-6848eca1ead4> in <module>()
----> 1 type(y)

NameError: name 'y' is not defined

Strings

Strings are the variable type that is used for storing text.

In [5]:
s = "Hello world"
type(s)
Out[5]:
str

To get the number of characters in a string variable you can use the function len():

In [6]:
len(s)
Out[6]:
11

To replace a substring in a string with another substring;

In [7]:
s2 = s.replace("world", "Basel")
print(s2)
Hello Basel

Numbers and Basic Math Operators

The two most common data types used to represent numbers are integers and floats. Integers are whole numbers without a fractional part (e.g. 2, 4, -20) and have type int. Numbers with a fractional part (e.g. 5.0, 1.6) have type float.

In [8]:
n = -1
type(n)
Out[8]:
int
In [9]:
m = -1.0
type(m)
Out[9]:
float

Basic math operators include +, -, * and / :

In [10]:
5 + 7
Out[10]:
12
In [11]:
5 - 7
Out[11]:
-2
In [12]:
5 * 7
Out[12]:
35
In [13]:
5 / 7
Out[13]:
0.7142857142857143

The order of operators is standard and parentheses () can be used for grouping:

In [14]:
(50 - 5 * 6) / 4
Out[14]:
5.0

The division operator / returns a float. To do a division and get an integer result you can use the // operator which rounds down the result to the nearest integer. To calculate the remainder you can use %:

In [15]:
7 // 5
Out[15]:
1
In [16]:
7 % 5
Out[16]:
2

The ** operator is used to calculate powers:

In [17]:
5 ** 7
Out[17]:
78125

As seen above, the equal sign = is used to assign a value to a variable:

In [18]:
a = 5
b = 7
c = a / b
In [19]:
c
Out[19]:
0.7142857142857143

Booleans and Logical Operators

A data object of type Boolean can take the values True or False:

In [21]:
a = True
type(a)
Out[21]:
bool

When used in arithmetic operations, True is converted to 1 and False is converted 0.

In [22]:
b = False
a + b
Out[22]:
1
In [23]:
a * b
Out[23]:
0

The logical operators are and, not, or:

In [1]:
True and True
Out[1]:
True
In [25]:
not True
Out[25]:
False
In [26]:
True or False
Out[26]:
True

The standard comparison operators are >, <, >= (greater or equal), <= (less or equal), == equality. These operators return a value of type Boolean (True or False):

In [27]:
a, b = 1, 2

a < b
Out[27]:
True
In [28]:
a > b
Out[28]:
False
In [29]:
c = 0

c < a < b
Out[29]:
True
In [30]:
d = 3

d == 1
Out[30]:
False
In [31]:
d != a
Out[31]:
True

The above can be combined using the boolean operators:

In [32]:
a >= 0 and a != 0
Out[32]:
True

Container types

Lists

The first container type we look at is list. Lists are native Python data structures used to group a collection of objects.

In [33]:
l = [a, 15, 'foo', True]
l
Out[33]:
[1, 15, 'foo', True]
In [34]:
type(l)
Out[34]:
list

To add elements to a list, use the list method append:

In [35]:
l.append('bar')
l
Out[35]:
[1, 15, 'foo', True, 'bar']

To remove an element you can use the list method remove applied to the element value:

In [36]:
l.remove('bar')
l
Out[36]:
[1, 15, 'foo', True]

or the function del() combined with the element's position in the list:

In [37]:
del(l[0])
l
Out[37]:
[15, 'foo', True]

Indexing in Python is zero based (starts from 0), similar to C, C++, Java, etc.

In [38]:
l[0]
Out[38]:
15
In [39]:
l[1]
Out[39]:
'foo'

Lists are mutable:

In [40]:
l[2] = 'foobar'
l
Out[40]:
[15, 'foo', 'foobar']

Tuples

Tuples are similar to lists except they are immutable. Notice the use of round (or no) brackets for tuples as opposed to square brackets for lists:

In [41]:
t = (a, 15, 'foo', True)
t
Out[41]:
(1, 15, 'foo', True)
In [42]:
t = a, 15, 'foo', True
t
Out[42]:
(1, 15, 'foo', True)
In [43]:
type(t)
Out[43]:
tuple
In [44]:
t[2]
Out[44]:
'foo'
In [45]:
t[0] = 'foobar'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-45-5d00ce945170> in <module>()
----> 1 t[0] = 'foobar'

TypeError: 'tuple' object does not support item assignment

Tuples and lists can be unpacked as follows:

In [46]:
a, b, c, d = t
print(a)
print(b)
print(c)
print(d)
1
15
foo
True

Dictionaries

Dictionaries are similar to lists and tuples except that items are indexed by names:

In [47]:
d = {'beta':0.96,'alpha':0.8,'tau':0.30}
d
Out[47]:
{'alpha': 0.8, 'beta': 0.96, 'tau': 0.3}
In [48]:
type(d)
Out[48]:
dict
In [49]:
d['beta']
Out[49]:
0.96

Adding an entry to a dictionary is very intuitive:

In [50]:
d['theta'] = 0.5
d
Out[50]:
{'alpha': 0.8, 'beta': 0.96, 'tau': 0.3, 'theta': 0.5}

Dictionaries are mutable:

In [51]:
d['beta'] = 0.99
d
Out[51]:
{'alpha': 0.8, 'beta': 0.99, 'tau': 0.3, 'theta': 0.5}

In scientific computing, you can use lists to store results and dictionatries to store sets of parameters. Tuples are less used but still important to know since they are returned as output by many numerical functions as we will see later on.