*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.
Common data types in Python include:
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:
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).
You can create a variable just by assigning a value to it. The assignment operator in Python is =
x = 1
x
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.
type(x)
int
If you try to use a variable that has not yet been defined you will get a NameError
:
type(y)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-4-6848eca1ead4> in <module>() ----> 1 type(y) NameError: name 'y' is not defined
Strings are the variable type that is used for storing text.
s = "Hello world"
type(s)
str
To get the number of characters in a string variable you can use the function len()
:
len(s)
11
To replace a substring in a string with another substring;
s2 = s.replace("world", "Basel")
print(s2)
Hello Basel
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
.
n = -1
type(n)
int
m = -1.0
type(m)
float
Basic math operators include +, -, * and / :
5 + 7
12
5 - 7
-2
5 * 7
35
5 / 7
0.7142857142857143
The order of operators is standard and parentheses ()
can be used for grouping:
(50 - 5 * 6) / 4
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 %
:
7 // 5
1
7 % 5
2
The **
operator is used to calculate powers:
5 ** 7
78125
As seen above, the equal sign =
is used to assign a value to a variable:
a = 5
b = 7
c = a / b
c
0.7142857142857143
A data object of type Boolean can take the values True
or False
:
a = True
type(a)
bool
When used in arithmetic operations, True
is converted to 1 and False
is converted 0.
b = False
a + b
1
a * b
0
The logical operators are and
, not
, or
:
True and True
True
not True
False
True or False
True
The standard comparison operators are >, <, >= (greater or equal), <= (less or equal), == equality. These operators return a value of type Boolean (True
or False
):
a, b = 1, 2
a < b
True
a > b
False
c = 0
c < a < b
True
d = 3
d == 1
False
d != a
True
The above can be combined using the boolean operators:
a >= 0 and a != 0
True
The first container type we look at is list
. Lists are native Python data structures used to group a collection of objects.
l = [a, 15, 'foo', True]
l
[1, 15, 'foo', True]
type(l)
list
To add elements to a list, use the list method append
:
l.append('bar')
l
[1, 15, 'foo', True, 'bar']
To remove an element you can use the list method remove
applied to the element value:
l.remove('bar')
l
[1, 15, 'foo', True]
or the function del()
combined with the element's position in the list:
del(l[0])
l
[15, 'foo', True]
Indexing in Python is zero based (starts from 0), similar to C, C++, Java, etc.
l[0]
15
l[1]
'foo'
Lists are mutable:
l[2] = 'foobar'
l
[15, 'foo', 'foobar']
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:
t = (a, 15, 'foo', True)
t
(1, 15, 'foo', True)
t = a, 15, 'foo', True
t
(1, 15, 'foo', True)
type(t)
tuple
t[2]
'foo'
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:
a, b, c, d = t
print(a)
print(b)
print(c)
print(d)
1 15 foo True
Dictionaries are similar to lists and tuples except that items are indexed by names:
d = {'beta':0.96,'alpha':0.8,'tau':0.30}
d
{'alpha': 0.8, 'beta': 0.96, 'tau': 0.3}
type(d)
dict
d['beta']
0.96
Adding an entry to a dictionary is very intuitive:
d['theta'] = 0.5
d
{'alpha': 0.8, 'beta': 0.96, 'tau': 0.3, 'theta': 0.5}
Dictionaries are mutable:
d['beta'] = 0.99
d
{'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.