# Addition
1 + 1
2
ACTL3143 & ACTL5111 Deep Learning for Actuaries
You can use Google Colaboratory to run Python. Eventually you’ll want to run Python on your own computer though. In Week 1, follow along this video to get everything installed to run Python on your home computer.
In this module we will be introducing you to Python, covering fundamentals such as variables, control flow, functions, classes, and packages. You should all be familiar with the language R. R shares many similarities with Python, including some syntax, data types, and uses - R and Python are the two most popular languages for data science [source: edx.org]. Because of this, you should be able to easily understand the basics of Python, and in this lab, we will make some references to R.
Much like with R, Python can also be used as a calculator:
# Addition
1 + 1
2
# Subtraction
9 - 6
3
# Multiplication
12 * 8
96
# Division
54 / 18
3.0
# Modulo
39 % 8
7
# Brackets
3 * (4 + 5)
27
# Powers - note that unlike R, Python uses "**" to denote powers
4 ** 3
64
Assigning values to variables is easy:
= 1
a print(a)
1
= 2
a = 3
b = a
b print(b)
2
Types of variables in Python include:
int
float
string
bool
NoneType
You can check the type of a variable by using the type()
function:
print(type(1))
print(type(1.0))
print(type("Hello World!"))
print(type(1 == 1.0))
print(type(None))
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'NoneType'>
= 1
x += 2
x print(x)
3
= 1
x -= 2
x print(x)
-1
= 1
x *= 2
x print(x)
2
= 1
x /= 2
x print(x)
0.5
Much like in R, you can encode strings by using single or double quotation marks:
= "Hello" s1
= 'World!' s2
You can concatenate strings by using the +
operator:
+ " " + s2 s1
'Hello World!'
F-strings are one of the ways you can substitute the values of variables into a string:
f"{s1} {s2}"
'Hello World!'
In Python, the logical operators and
, or
, and not
are used. This is unlike in R, in which the symbols &
, |
, and !
are used.
True and False
False
True or False
True
Use the functions int()
, float()
, and str()
to convert values from one type to another:
= 3
x = str(x)
x print(x)
3
is.string()
to determine whether a value is a string. Unfortunately, there isn’t a similar function in Python. Can you figure out a way to check whether a value is a string in Python? What about an integer, or a bool?type(type(bool(int("3"))))
?not(True and not False or False and not (True or False))
?5*(2+4**3)
330
= "Hello"
x
print(x == str(x))
True
type(type(bool(int("3"))))
type
not(True and not False or False and not (True or False))
False
There are four types of built-in data structures available in Python: lists, dictionaries, tuples, and sets.
Lists are very much like R vectors, in which they hold a series of values of any type. Lists in Python can be altered, whether it be by deleting or adding elements, or by editing specific elements inside the list. This feature is known as mutability. You will later see that some of the other Python data structures do not have this feature.
= [1,2,3,4,5] l
Tuples are similar to lists, except that they are immutable, i.e. they cannot be altered.
= (1,3) t
Dictionaries are a type of data structure that stores data in key-value pairs.
Dictionaries are mutable, however, you cannot change the name of a key.
= {
wam_dict "Alice": 87.4,
"Bob": 77.9,
"Charlie": 81.3
}
Sets are a type of unordered data structure that store a collection of unique values. You cannot change the specific values inside a set, but you can remove and insert elements.
= {"Apple", "Banana", "Strawberry"}
fruits print(fruits)
"Mango")
fruits.add(print(fruits)
"Banana")
fruits.add(print(fruits) #This will not return an error, but the duplicate element will not be added
"Apple")
fruits.remove(print(fruits)
{'Banana', 'Strawberry', 'Apple'}
{'Banana', 'Mango', 'Strawberry', 'Apple'}
{'Banana', 'Mango', 'Strawberry', 'Apple'}
{'Banana', 'Mango', 'Strawberry'}
l
.sort()
method.insert()
method.reverse()
.pop()
on the list twice.remove()
to remove the number 11 from the list.shapes
.sides
.shapes
and sides
using dict(zip())
. Print the dictionary."Pentagon": 5
to this dictionary to show that it is mutable. Print the dictionary.In Python, note the use of elif
rather than else if
. Also, note that Python uses indentation (as opposed to braces in R, C++, JavaScript, and other langagues) to denote different blocks of code.
= -30
profit
if profit >= 0:
print("Profitable")
elif profit == 0:
print("Break even")
else:
print("Loss")
Loss
You can use for
loops in Python to iterate through each value in a list, tuple, or other collection.
= ["ACTL1101", "ACTL2111", "ACTL2131", "ACTL2102"]
actl_core
for course in actl_core:
print(course)
ACTL1101
ACTL2111
ACTL2131
ACTL2102
You can also use for
loops to iterate through a sequence of numbers by creating the range()
object.
for i in range(5):
print(i ** 2)
0
1
4
9
16
while
loops can be used to perform the same tasks as for
loops, however, they tend to be more cumbersome to put together.
= 0
i
while i < 5:
print(i ** 2)
+= 1 i
0
1
4
9
16
while
loops are useful, however, for creating “sentinel” loops, in which a loop runs until a variable reaches a specified value called a sentinel:
= [9, 9, 6, 7, 3, 10, 0, 1, 4, 6, 2]
scores print(sum(scores))
= 0
i = 0
pre_fail_score
while scores[i] != 0: # 0 is a sentinel value
+= scores[i]
pre_fail_score += 1
i
print(pre_fail_score)
57
44
break
and continue
statements in Python.3, 7, -9, 11, 2, -5, 0, 4
.sum_pos
, and set it equal to 0.sum_pos
.continue
statement.break
.Functions are instantiated using the def
keyword.
def addOne(x = 0):
return x + 1
print(addOne(10))
print(addOne()) #Using default arguments
11
1
factorial(n)
, that takes in one input n
, and returns n!
.fibonacci(n)
, that takes in one input n
, and returns the n
th Fibonacci number.