# Addition
1 + 12
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 + 12
# Subtraction
9 - 63
# Multiplication
12 * 896
# Division
54 / 183.0
# Modulo
39 % 87
# Brackets
3 * (4 + 5)27
# Powers - note that unlike R, Python uses "**" to denote powers
4 ** 364
Assigning values to variables is easy:
a = 1
print(a)1
a = 2
b = 3
b = a
print(b)2
Types of variables in Python include:
intfloatstringboolNoneTypeYou 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'>
x = 1
x += 2
print(x)3
x = 1
x -= 2
print(x)-1
x = 1
x *= 2
print(x)2
x = 1
x /= 2
print(x)0.5
Much like in R, you can encode strings by using single or double quotation marks:
s1 = "Hello"s2 = 'World!'You can concatenate strings by using the + operator:
s1 + " " + s2'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 FalseFalse
True or FalseTrue
Use the functions int(), float(), and str() to convert values from one type to another:
x = 3
x = str(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
x = "Hello"
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.
l = [1,2,3,4,5]Tuples are similar to lists, except that they are immutable, i.e. they cannot be altered.
t = (1,3)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.
fruits = {"Apple", "Banana", "Strawberry"}
print(fruits)
fruits.add("Mango")
print(fruits)
fruits.add("Banana")
print(fruits) #This will not return an error, but the duplicate element will not be added
fruits.remove("Apple")
print(fruits){'Strawberry', 'Apple', 'Banana'}
{'Mango', 'Strawberry', 'Apple', 'Banana'}
{'Mango', 'Strawberry', 'Apple', 'Banana'}
{'Mango', 'Strawberry', 'Banana'}
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.
profit = -30
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.
actl_core = ["ACTL1101", "ACTL2111", "ACTL2131", "ACTL2102"]
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.
i = 0
while i < 5:
print(i ** 2)
i += 10
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:
scores = [9, 9, 6, 7, 3, 10, 0, 1, 4, 6, 2]
print(sum(scores))
i = 0
pre_fail_score = 0
while scores[i] != 0: # 0 is a sentinel value
pre_fail_score += scores[i]
i += 1
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 arguments11
1
factorial(n), that takes in one input n, and returns n!.fibonacci(n), that takes in one input n, and returns the nth Fibonacci number.