Python summary
Lecture 1
Assign a value to variable “my_first_variable” (same as <- in R)
my_first_variable = 5
Variables are usually in lower case letters in python.
Data types
Integer (int): 5
Float (float): 1.5
String (str): text
Boolean (bool): True/False (first letter needs to be capitalized)
Nothing: None (is NULL in other languages)
Collections
Collections can hold 0, 1 or more elements of any data type
Sequences: Values are stored in a given order
o List: [1,2,3]
o Tuple: (1,2,3)
o Range: lazily populated tuple
Sets: Only unique elements
o Set: {1,2,3}
Dictionaries: key value mappings
o Dict: {1: ‘a’, 2: ‘b’)
o Create a new one with dict() or {}
Numeric operations
Multiplication
o Var1 * Var2
Division
o Var1 / Var2
o Division without remainder (e.g. .33) Var1 // Var2
Remainder
o 3%4=3
o 5%4=1
Addition & Substraction
o Var1 + Var2
o Var1 – Var2
Power
o 3 ** 2
Boolean operations
o True and False
o True and True
o False and False
o Or
o True or False
o False or False
o Or
o Not True
o Not False
,Concatenations
Var1 + Var2
o ‘Var1Var2’
You can also do something like: print(Var1 + ‘ ’ + Var2) to get a space in between them. The
variables need to be string otherwise you need to state str(Var1).
Combined operations/assignments
Assignments is when an = is involved. You can combine assignments with operations
Var1 += var2
o Above is shorthand for var1 = var1+var2
o Increases readability of the code
Escaping
For strings both ‘ ‘ or “ “ work. Does not matter really which one to use. But stick to ‘ ‘ for
internal code. So for strings in this course only use ‘ ‘.
If you want to include a text with quote e.g. customer’s use: ‘Customer\’s’
Formatting strings
How to put a sentence: there are 55 students in this class
o Num_stud is a variable that holds the number 55
Use formatting syntax (f)
o F’There are (num_stud) students in this class.’
When you have a very long integer that isn’t easily readable e.g. 8.3444
Use :.2f
o F’there are (num_stud:.2f) students in this class’
o Output: There are 8.33 students in this class
To get the index of a number use:
Variable_name.find() for the first index number. Between brackets put the letter or number
you are looking for.
Variable_name.rfind() for the last index number.
If you do not want the number, but the piece of text use:
s[:s.find('h')]. So: put the thing in square brackets and add the variable name again before it.
If you want the letters before the occurrence of h use the semicolon : before it. Otherwise
after it.
last = s[s.rfind('h') + 1:] you can also put +1 or -1 if you want to go one letter extra for
example.
Variable lists
Most commonly used in Python (lesson 5 of lecture 1)
A = [1, 2, 3]
Or
A = [1, ‘a’, 3]
Python starts counting from 0. So if you want the first variable in the list:
o A[0] gives
o 1
Len() function gives the length of a list
o Len(a) = 3
Slicing: Slice lists in the form of “from1to4” so include the first 4 values, the to element is
excluded so it isn’t “tot en met”
o A[0:4]
o [1,2,3,4]
Slicing can also be in steps
, o A[:] means we take the entire list
o Output: [1,2,3,4,5]
o A[::2] means we want to take steps of 2 and start at 0
o Output: [1,3,5]
Negative indices also exist, then you count from the back
o A[-1] gives 5 (from list 1 to 5)
Check if an element is in list function “in”
o 1 in a
o Output: True
If you want to count how often something occurs:
o A.count(1)
o Output: 1
If you want to see which value first occurs
A.index(1)
o Output: 1
Modifying lists: lists are mutable
o Change the first element in the list:
A[0] = 4
A[4,1,2,3,4,5]
Appending lists
o A.append(6) means we are adding 6 to the list
o A[4,1,2,3,4,5,6]
Or with slicing:
o A[len(A):] = [7]
o A[4,1,2,3,4,5,6,7]
Concatenate lists:
o A+B
o Output: [5,1,2,3,4,5,6,7,’a’,’b’]
Removing elements from lists:
o A.remove(7)
o A[4,1,2,3,4,5,6]
Del function can also be used
o Del a[0] removes the first value in the list
o A[1,2,3,4,5,6]
Shallow copies and nesting
B.copy()
Nesting: put a list into another list
o B[0] = [‘a’,’b’,’c’]
o [[‘a’,’b’,’c’],’b’,3]
If you want to remove a value from a string: delete value: use replace. First one is the character you
want to delete, second one is nothing so you replace it with nothing.
print(s.replace('@', ''))
Tuples
Are like lists, but you cannot change them they are immutable. Everything works exactly the same
but you use () instead of [].
Ranges: Are lazily populated integer tuples. They cannot be changed and not all elements are
immediately there, they are only created when its needed.
Range(5) gets
o Range(0, 5)
When you make it a tuple again
, o Tuple(range(5))
o (0,1,2,3,4)
Replace function can alter strings
Change all a values in tuple ‘a’: A.replace(‘a’, ‘d’)
Slide “Sequence ops” summarizes all functions for lists.
Sets
(number 8 from lecture 1 github). Sets can only contain unique elements
A = {1,2,3}
In function to see if a value is in the set
o 1 in a
o True
Union: | to add all elements from one set to another
o A|b
o {1,2,3,4,5}
Sets can also be mutated
o A.add(6)
o {1,2,3,4,5,6}
Dictionaries
(number 9 from lectue 1 github) used to map keys to values
A = {‘a’:1,’ b’:2,’ c’:3)
o A B and C are keys in this statement, 1 2 and 3 are the values
Also can be done with the dict() function
o B = dict(d=4, e=’g’, f=True)
Get all keys with: keys() function
o A.keys()
Get all values with: values() function
o A.values()
Get all key-value combinations as tuples:
o A.items()
Functions
Object functions are functions executed on an object e.g. a.append to add an element to a list.
Function sorted([2,1,3]) gives a new list:
o [1,2,3]
Max function for maximum value Max_age = max([1,2,3])
o Max_age
o 3
Type(): find the type of a variable (e.g. integer)
Non-object functions: Functions can also exist without reference to any class or object
Len(‘abc’)
o 3
Min([1,2,3])
o 1
Sum([1,2,3])
o 6
Type conversion: Functions that convert one data type to another
When you have numbers as string values you can convert them like:
o Int(‘1’)
o Float(‘1.5’)
o Bool(‘True’)