Exercise Set I - Python
Jupyter Google Colab 💡 Show Hints ℹ️ Show Solutions
Exercise 1
Define the following object types. Moreover, provide one example of each.
Dictionaries
Lists
Floating-point numbers
Tuples
Think about how different data types are constructed in Python. Use curly braces {}
for key-value mappings, square brackets []
for ordered collections, parentheses ()
for immutable sequences, and decimal notation for floating-point numbers.
Dictionaries: Python dictionaries are known as mappings. As lists, mappings are collections of objects. Moreover, dictionaries are also mutable, meaning that they can be changed in-place and they can grow/shrink on demand. The difference between dictionaries and lists is that objects in dictionaries are stored by key instead of by relative position.
Lists: Lists represent the most general sequence in Python. Moreover, lists are mutable.
Floating-point numbers: Floating-point numbers are numbers with a decimal point in them (like 754.7, 32.453, and 5.675).
Tuples: In simple words, we can define tuples as immutable sequences. That is, we can think of a tuple as a list that cannot be changed. Tuples are coded in parentheses (instead of square brackets as for lists). Furthermore, tuples support arbitrary types, arbitrary nesting and the usual sequence operations.
Exercise 2
Indicate the data type of each of the following values. Then use the type()
function to verify your assertion.
‘Social Insurance’
123.0
“123”
‘123’
123
Use the type()
function to verify your predictions. Remember that quotes determine strings, decimal points determine floats, and whole numbers without quotes are integers.
The data types of each of the values above are the following ones:
string
float
string
string
integer
Let’s validate our assertion using the type()
function:
Exercise 3
Indicate the data type of each of the following results of operations. Then use the type()
function to verify your assertion. Do they all work?
4 / 2.0
5 // 2.0
“Actuarial” + “Data Science”
2 + 3.0
65 + 3
“30” + 3
Test each operation and use type()
to check the result. Pay attention to Python’s type coercion rules and remember that some operations between incompatible types will raise errors.
The data types of each of the operations above are the following ones:
float
float
string
float
integer
error
Let’s validate our assertion using the type()
function:
Exercise 4
Which of the following variable names are acceptable and which are not? If one of these names is unacceptable, explain why.
COUNTRY
lambda
loss 1
loss_1
1st_loss
PolicyID
zipcode
_carmodel
Consider Python’s variable naming rules: valid identifiers must start with a letter or underscore, cannot contain spaces, and cannot be reserved keywords. Test problematic names by trying to assign values to them.
All the names are acceptable except for lambda
, loss 1
and 1st_loss
. The first one (lambda
) is not acceptable as in Python, we use the lambda
keyword to define an anonymous function. The second one (loss 1
) is not acceptable as spaces are not allowed in variable names (e.g. we can use underscores instead of spaces). On the other hand, the third one (1st_loss
) is not acceptable as a variable name must start with a letter or the underscore character. A variable name cannot start with a number.
Let’s validate our previous assertion using some code:
Exercise 5
Run the following lines of code and indicate the final value of x
. Can you explain in more detail what each line of code does?
x = 22
x-=1
x//=4
x*=3
x+=7
Work through each compound assignment operator step by step. Remember that //
performs floor division. Execute each line and track the value of x
after each operation.
Exercise 6
As we discussed in the lecture, in Python, the data type of a variable is dynamically inferred. Run the following statement: z = 8
. Then, use the type()
function to check its data type. What data type is it? Now, increment z
by 2
, using the +=
operator, then check its data type again. Did it change? What data type is it now? Increment z
by 2.0
(again using the +=
operator), then check its data type again. Did it change? What data type is it now?
Use type()
after each operation to observe how Python’s dynamic typing works. Pay attention to what happens when you mix integers and floats in arithmetic operations.
The data type of z
is integer
.
The data type of z
did not change. As we are adding two integers
(z
plus 2
), it is still an integer
.
The data type of z
changed. As we are adding an integer
with a float
(z
plus 2.0
), it is now a float
.
Exercise 7
Using Python, calculate the present value of the following cashflows using a constant force of interest of \(δ = 0.07\%\) per month:
CHF 20 in 7 months, followed by
CHF 45 in 4 years.
The present value is calculated as follows: \[\text{Present 𝑉alue} = 18e^{−0.002×18} + 30e^{−0.002×48} \approx 44.62\]
For \(r=e^{-0.002}-1 \approx 0.2002 \%\), we have \[\text{Present 𝑉alue} = \sum_{i=1}^{48}1 \cdot (1+r)^{-i} = \frac{1-(1+r)^{-48}}{r}\]
Exercise 8
Define the variables a = estimator
, b = biased
and c = ho
. What is the result of each statement? Which do not work, and why?
b + ” ” + a
a + ” ” + b
c * 7
a * c
a + 8
b + “8”
Remember to define your string variables with quotes. Test each operation and observe which combinations of strings and numbers are valid in Python. Some operations will work, others will raise errors.
(a)
(b)
(c)
(d)
(e)
(f)
Exercise 9
Explain why the following error occurs:
Examine the variable names carefully. Python is case-sensitive, so loss
and Loss
are treated as different variables. Check what was defined versus what was accessed.
The error occurs because the variable Loss
is not defined. Indeed, we previously created a variable named loss
but we are trying to increase by one the variable Loss
which does not exist. Let’s try to reproduce the error:
Exercise 10
Select a meaningful variable name that represents the following situations:
The total number of claims incurred by an insurance company
The total losses incurred by an insurance company
The age of a policyholder
The Policy ID of an insurance card
Choose descriptive names that clearly communicate what each variable represents. Use lowercase with underscores for multi-word variables. Think about how you would naturally describe each concept.
(a) claims
(b) losses
(c) age
(d) policy_id
Summary
These exercises, albeit very basic, covered the essential Python fundamentals for data science and actuarial work:
- Data Types: Dictionaries, lists, tuples, and floats for different data structures
- Type System: Dynamic typing, type coercion, and error handling
- Variables: Naming conventions and Python syntax rules
- Operations: Arithmetic operators and string manipulation
- Applications: Present value calculations and actuarial problem-solving
These fundamentals prepare you for NumPy arrays, Pandas DataFrames, and data visualization.