In this short crash course we will learn to code in Python programming language, specifically we will use Python 3, while searching on the internet you may sometime stumble upon Python 2.7. There are a few syntactic differences you will learn along the way.
Variables are boxes labeled with name used to store values. Each variable is of a specific type, the types define the operations that can be applied to the variables and their response to them. The most common variable types are:
# This is a comment, text following a hashtag is not interpreted as code.
"""This is also a comment,
it is a string,
and can span multiple lines."""
# To execute the code in a cell, press ctrl-shift
a = 5 # the variable a is assigned the value 5
type(a) # a is variable of type "int", short for integer
# python automatically guesses the variable type of your input, can you google what this variable type stands for?
b = 0.2
type(b)
In order to print out the value of a variable or a calculation, you can use the function print()
print(a) # don't forget the brackets ()!
print(a + 15)
a = 5
print(type(a))
a = "hello"
print(type(a))
Guess the results of the following operations, write them down before running the cell!
a = 5
print(a / 2)
print(a // 2) # // signifies whole number division
print(a % 2) # % is the remainder after division
Write a code to print the sum of the variable a
and b
:
# CODE HERE
Python can also work as a very powerful calculator, what is 99 to the power of 99? (Hint: powers are denoted by ** in Python)
# CODE HERE
Python also supports scientific notation (e.g. 4x10^2)
4e2
It is possible to add different types in Python, the resulting type is chosen automomatically. (broadcasting)
my_str = 'str' # string
my_int = 4 # int
my_float = 4.5 # float
my_bool = True # bool (logic value True / False)
print(my_int + my_float)
print(my_float + my_bool)
print(my_str + my_int)
Some types cannot be added together as you can see above! Also notice that when adding a float and an int, the result is chosen to be a float.
String is a data type used to represent text in Python:
c = "abc"
type(c)
There is an arithmetic associated to the string data type, see how a string behaves under the following operands:
hello = "Hello"
space = " "
world = "World!"
print(hello + space + world)
print((hello + space) * 2 + world)
print("-" * 50)
Notice that the sign "+" concatenates strings, but adds numbers when applied to int
s or float
s. An operator with different operations for different types is called an "overloaded operator". It is possible to manually change the data type of a variable, for example strings to integers or floating-point numbers.
s = "123"
si = int(s) # string s converted to an integer
print(si)
sf = float(s) # string s converted to a floating point number
print(sf)
... or vice-versa:
d = 123
ds = str(d)
print(ds + "_" + "s")
# Another way of combining other data types (int, float etc...) with strings:
print("some int: {}, some float: {}".format(2, 2.5))
Finally, strings can be split into lists!
s = "123"
print(len(s)) # How long is this string?
list(s)
List is a mutable sequence of elements, i.e. once created, the separate elements can be changed. Lists can be created in the following way a = [1,2,3]
a = [1, 2, 3]
print(a)
b = [2, 5]
print(a + b) # Lists can be added together, this appends list b to list a!
print(a * 5) # List can also be repeated as we did with strings
Try if lists can be subtracted or multiplied!
# CODE HERE
Elements in a list can be accessed separately, each element has an associated index starting from 0
a = [1, 2, 3]
print(a[0]) # first element is numbered by 0, not 1!
print(a[-1]) # last element of the list
a[0] = 5
print(a) # we have modified the first element
Try accessing the 10th element in list 'a' :
# CODE HERE
a[10]
Can you use your python knowledge of lists and strings to find the 10th character in the sentence below?
this is a string with an exciting 10th character!
# CODE HERE
Below you can see some handy functions that can be perfomed on a list:
# length of a list
a = [1, 2, 3]
print(len(a))
# sum of all list elements
sum(a)
print(sum(a))
# adding an element to the list
a.append(10)
print(a)
Especially useful is the sort() function:
v = [5, 3, 8, 1]
print(v)
v.sort()
print(v)
print(list(reversed(v)))
# Try to print out the result of the function reverse() without converting to list. What type is it?
The elements in a list do not need to be all of the same type.
good_list = ['Data Science', 485, True, 0.001]
print(good_list)
Lists can also contain more lists, exciting! Let's append a list at the end of a list:
good_list = ['Data Science', 485, True, 0.001]
good_list.append(['first', 'list'])
print(good_list)
last_elem = good_list[-1]
print(last_elem)
print(last_elem[0])
print(good_list[-1][0]) # picks the first element of the last element of good_list
How many elements does the list [[0,1,2,3,4,5,6]]
have? Use the len()
function to see if you were right.
# CODE HERE
a = [[0,1,2,3,4,5,6]]
range()
is a particularly useful iterator that can be converted into a list:
r = range(10)
print(r)
In the future you will see that the result of the range()
function behaves just like a list would when combined with certain functions or in loops. If you want the result to really be a list, make sure to convert it!
r = range(10)
r = list(r)
print(r)
print("length: {}, sum: {}".format(len(r), sum(r)))
The range()
function can have a specified start, end and step size. The syntax is: range(first element, last element, step size)
print(list(range(1,10,2)))
print(list(range(10,1)))
print(list(range(10,1,-1)))
a=range(5)
print(a)
print(a[2])
print(type(a)) # range() does not result in a list, unless explicitly converted!
Create a list of all the multiples of three between 1000 and 2500:
# CODE HERE
You have already seen how to access a single element in a list:
a = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 9]
print(a[0])
print(a[1])
print(a[len(a) - 1])
print(a[-1])
In python, you can also access "sublists" of lists, the syntax is: list[ start : end : step ]
print(a[0:2]) # first two elements
print(a[:2]) # from the start to element two
print(a[7:]) # from element seven to the end
print(a[-2:])
print(a[::2]) # every second element from the start to the end
Create a list containing 11 elements, print out the following sublists: - All elements between the 2nd and 5th element - Every second element of the list - Print out the whole list backwards - Exchange the order of the 4th and 5th element and the 8th and 9th element.
# CODE HERE
In Python it is often necessary to write down conditions which result in a boolean value (either False
or True
). It is important to learn how to evaluate such conditions using basic logic. Let's look at some logic operations first:
print(True or False)
print(False or False)
print(True or True)
print(False and False)
print(True and True)
print(True and False)
print(not False)
print(not True)
These logical operations can be incorporated in terms of mathematical operations, let's define a few variables:
a = 5 # an integer
b = 6 # another integer
c = [0,1,2,3,4,5] # a list
Now we can test a few logic operations on these variables, look at the cell below and try to guess the output! Write your guesses down before running the cell!
print(a == b) # a equal to b
print(a + a == b) # 2a equal to b
print(a != b) # a not equal to b
print(a > b) # a greater than b
print(a < b) # a lesser than b
print(a <= b) # a lesser or equal to b
There are a few more intuitive operations that will come handy later on:
print(a in c)
print(b in c)
print(a not in c)
print(b not in c)
print(a and b in c)
print(a or b in c)
print(2 is '2')
print("2" is '2')
print(2 is not '2')
Make sure you understand each of the above results, if you don't, ask one of the demonstrators.
Conditional statements are useful when we want to run some parts of the code only if some conditions are fulfilled. The syntax is:
if [Condition]: [Code]
If the [Condition]
in the if statement has the value True, the [Code]
will be executed, otherwise it will not.
# Lets start with a few simple conditional statements
if True:
print("The condition after \"if\" is true!")
if False:
print("The condition after \"if\" is false :( !")
# It is possible to include a number of conditions! If neither is true, then the code in else will run.
a = 5
if a == 2:
print("a is equal to two!")
elif a == 3 or a == 4:
print("a is equal to three or four?")
else:
print("a is not two, three or four!")
Write a code that takes a list with n elements on its input, and returns the string "Too long"
if the n > 10, "Too short"
if n < 10, and "Ideal"
if n = 10.
# CODE HERE
Loops are one of the most important structures you will learn today, they allow cerain parts of the code to be executed multiple times. In Python the for
loop is used extensively. The syntax is: for <variable> in <list of elements>:
# one by one each element of the list is assigned to the variable i, then the code inside the for loop is executed
for i in range(10):
print(i, i**2)
# The loop iterates over the list, sequentially assigning values to the variable i. The code within the loop prints the value.
for i in [4, 1, 5, 22, 5]:
print(i)
for i in "abc": #it is also possible to iterate over strings
print(i)
# sometimes it is useful to have two nested for loops, keep in mind the more nested loops the slower the code!
for i in [1,2,3]:
for j in range(2,22,5):
print(i, j)
If you encounter an expression such as this:
for item in list: if conditional: expression
It can be briefly written in python as:
[ expression for item in list if conditional ]
# You can either use loops:
squares = []
for x in range(10):
squares.append(x**2)
print(squares)
# Or you can use list comprehensions to get the same result:
squares = [x**2 for x in range(10)]
print(squares)
Code a comprehension list that iterates over first 100 whole numbers and picks out the even ones:
# CODE HERE
While loop is a classic loop with a set condition, while the condition is true, the cycle will repeat.
i = 0
while i < 10:
print(i)
i = i + 1
If the while condition is always true, the cycle will never stop.
i = 0.0000000000000000000000000000000001
while i != 10:
i += 1
print(i)
Functions are a basic building block of a programming language. In python, functions can return multiple variables at the output. (unlike C/C++ and Fortran). The syntax is:
def [function name]( [inputs] ): [code within the function] return [output]
def plus(a, b):
return a + b
print(plus(1, 2))
print(plus(3.2, -1))
# functions can have default input values
def plus2(a, b=2):
return a + b
print(plus2(7))
print(plus2(7,4))
print(plus2(7,b=4))
Analyse the following function, what do you think it does? Use the function on a number of testcases to see if your guess is correct.
def num_sum(a):
summ = 0
for character in str(a):
summ += int(character)
return summ
num_sum(123)
Combine your knowledge of comprehension lists and functions to write a code that finds all the even numbers between n and m:
# CODE HERE
A bank provides ISA with 5% interest per annum. If you deposit 50 pounds a month into the ISA over the period of one year, and the money deposited in the account is compounded at the end of every month, how much money will be in the account at the end of the year?
# CODE HERE
# CODE HERE
# CODE HERE
Code a function that decides whether the input is a prime number or not.
Find the sum of the first 100 prime numbers.
# CODE HERE
Pandas is a library providing high-performance, easy-to-use data structures and data analysis tools for Python. In this section we will use Pandas only as means of importing and handling external files.