Python Notes
Python Notes
Some points were skipped because they were not relevant for this course. The exam
is on the 6th Novermber 2023.
-1. NOTEBOOK
We have code cells and text cells. Unless normal Python files, if an
instruction produces a result, it is printed as an output of the cell, even if it
has not been asked to print. A semicolon will not show the output. We have to pay
attention to the order of execution of the cells too. We can put curly brackets
inside a string in a print and then use the '.format()' to put the variables we
want to print as a tuple. Finally, we can get the documentation of a function with
'help(function)' or via Shift+TAB when the cursor is after the parenthesis.
0. MOTIVATION
It is for general purpose and inside we can use very interesting modules as
NumPy, MatPlotLib and Pandas.
1. INTRODUCTION
2. SYNTAX
2.1. IF
We use 'if (condition with > for example):'' and then what we want to
happen in the next line with indentation. Indentation must always be the same.
2.2. VARIABLES
2.3. COMMENTS
We can use '#' to start a comment that will occupy that code line.
3. COMMENTS
They can be used to explain some things in the code or just to not execute
them. You can use '#' at some point in a line of code and from there on the line
won't be read when executed.
You can also have a multi-line comment by using multiline string (triple
quotes) because Python ignores string literals that are not assigned to a variable.
'''
All
The
Comments
'''
4. VARIABLES
4.1. Variables
They contain data values and you have to give them a value to create
them. Their type can be changed by just giving it another value. We can give an
specific type by using the cast commands 'str()', 'int()' or 'float()'. The
'type()' function will just give you the type of the variable. We can use single or
double quotes indistinctly. Note that variables are case dependent.
They have to start with a letter or an underscore and can only have,
numbers, letters and the underscore. They cannot be keywords as 'if' or 'continue'.
We can assign multiple variables in one line or one value for different
variables.
We can also extract the variables from lists, tuples and others.
You just use the 'print()' command, with commas to print different
variables at the same time separated by a space. The '+' operator will put the
values together in the case of strings or will sum numerical values, but now we
cannot mix them.
global x
x = 3
5. DATA TYPES
6. NUMBERS
6.1. Integer
6.3. Complex
6.4. Conversion
You can convert integers and floats to all the other types.
To get a random number you have to import the random library with
'import random' and then you can get one between 1 and 10 with the command
'random.randrange(1,10)'. More info of this module in
https://www.w3schools.com/python/module_random.asp.
7. CASTING
We can make an integer from an integer, a float by removing all decimals and
a string if it is a whole number.
The same works with a float but the string can also be a float.
Strings can be made of a lot of variables, like integers, floats and other
strings.
8. STRINGS
help(str)
8.1. Strings
They are arrays and we access each item with '[]', starting the count
in 0.
We can loop in them, i.e. reading all the items of the array with the
for loop: for i in string.
We can also get the lenght as an integer with the function 'len()'.
8.2. Slicing
8.3. Modify
8.4. Concatenate
8.5. Format
8.7. Methods
import datetime
string = '01/01/2017 11:00'
date = datetime.datetime.strptime(string, '%d/%m/%Y %H:%M')
9. BOOLEANS
We can use this to evaluate any expression, such as a comparison between two
values with '<', '>' and '=='.
But we can also evaluate values and variables with the function
'bool(variable)'. Values that will be false are empty strings, numerical values
equal to 0, lists, tuples, sets or dictionaries that are empty, 'None' and 'False'.
An specific type of class (not seen) can also get this result. We can also get a
boolean returned from a function. There are plenty of built-in functions that can
return booleans.
10. OPERATORS
They are used to perform operations on variables and values. There are
groups:
11. LISTS
They store multiple items in a single variable and are created using '[]' and
the items separated by commas. They are ordered (then can be indexed), changeable
and allow duplicates. We can get the lenght with the 'len(list)' function and they
can contain different data types. We can also create them with the function
'list()' and putting literally a tuple inside, with the items separated by '()'
instead of '[]'.
We can access them with the indexing 'list[]' where the first item has
index 0 and negative ones start from the end. We can also get a sublist by
specifying a range '[start:end]' without the latter included. No value will mean
start or end. Negative indexes also work here. We can check if an item is inside
using 'in'.
The '.append(item)' will add the item at the end of the list. We use
'.extend(list)' to add a list or elements of it. We can extend with tuples,
dictionaries and sets too. Be careful not to extend with a non-iterable item, such
as a string.
11.4. Remove list items
We use 'for x in list' to loop through the list items. We can combine
it with 'range(len(list))' to do so with the indexes.
We can concatenate them with the addition operation '+', use the
'.append(item)' function in a loop or use '.extend(list)' to add the whole list all
at once. Remember that the extend function can be used with all iterables.
12. TUPLES
They store multiple items in a single variable and are created using '()' and
the items separated by commas. They are ordered (then can be indexed), UNchangeable
(no assignment nor addition) and allow duplicates. The lenght works as with lists.
To create a tuple with one item we must put a comma after that item, if not it
won't be recognised. The 'tuple()' constructor works analogously as the one for
lists.
13. SETS
They store multiple items in a single variable and are created using '{}' and
the items separated by commas. They are unordered, UNchangeable and don't allow
duplicates. Duplicated items will just not make it into the set. Recall that 'True'
and '1' are treated as the same value, so they are duplicate. The lenghts works as
seen earlier and we have the 'set()' building function.
We cannot search for them with indexing so we have to loop through them
or search with the 'in' function.
We cannot change items but we can add new ones with the function
'.add(item)'. We can add items to sets with the '.update(iterable)' function, where
we can use all types of iterables, not only other sets.
14. DICTIONARIES
They store data in key:value pairs. They are ordered (unordered until version
3.6), changeable and do not allow duplicates (we cannot have two identical keys).
They are created with '{key:value}' and the different pairs are separated by
commas. We refer to items by calling with their key names with the indexing syntax.
Length is obtained as always and the constructor is 'dict(key=value,)'
We can a list of the keys with the '.keys()' function. This is only a
view, so if there is a change on the dictionary, the variable in which we stored
this information will also change. Analogously, we will get a list of the values
with the function '.values()' and a list of tuples with the key and the value with
the function '.items()'. Recall that these are not really lists, so we cannot
access them through indexing unless we convert them to a list with the 'list()'
construction function.
We can either rewrite the value with the indexing or use the function
'.update({key:vaule})'. Recall it is written like a dictionary for the latter.
We use exactly the same method as for changing items. Simply, if they
do not exist, they will be created.
- Python 3 or newer:
import sys
version = sys.version_info[0]
print(version)
15. IF...ELSE
Logical conditions (equal, not equal, greater than, less than, greater than
or equal to and less than or equal to) can be used in if statements and loops.
The former are introduced with the keyword 'if', followed by the condition
and colon. Then, we must use an indentation to make Python know we are inside the
if statement. We can use, in the same indentation than the first if, two other
keywords: 'elif' for the case the previous conditions are not true and we want to
try another one and 'else' for the case none of the above conditions are true and
we want to do something with the remaining cases. The 'elif' is optional.
We can write the if statement in one line if there is only one statement to
execute, but using the same syntax.
We can also use logical operators to play with different conditions in the if
statement: 'and', 'or' and 'not' are the options we have.
We can have an if statement that does nothing, but we cannot leave it empty,
we write instead the keyword 'pass' inside it.
The two primitive loops commands are 'while' and 'for'. The former allows to
execute a set of statements as long as a condition is true. We have then to be
careful that the condition won't be satisfied at some point. The variable that sets
the loop must be ready before we start the loop.
The 'break' statement will stop the loop even if the condition is still true.
The 'continue' statement will just stop the current iteration and jump to the next
one.
An 'else' statement at the end will run a block of code once the condition is
no longer satisfied. A 'break' statement will not allow to run the 'else' block of
code.
The statements 'break' and 'continue' work as in the while loops, as well as
the 'else'.
We can also use nested for loops and the pass statement as before.
18. FUNCTIONS
They are blocks of code ran only by command. They receive data as
parameters and they execute a function and can return data as a result.
They are created with the 'def' keyword followed by the name and '()'.
We call the function by the name and also the parenthesis.
We can also use '*' in front of the parameter name if we don't know how
many arguments will be used. The function will transform the arguments into a tuple
and will access them accordingly, so the function must be written for a tuple
(indexing and so on).
If we write arguments with a key, then the order in which we call them
will not matter. For example we could call 'function(child1='Emil')', so inside the
function, the variable 'child1' will be for sure the one we give.
A default value can be set when defining the function and will be used
if no arguments are used.
Arguments can be any data types, but the function must be built
accordingly to that type.
Functions in Python accept recursion, which means that they can call
themselves. This allows to loop through data to get a result.
19. LAMBDA
Lambda is a function that can take any number of arguments but can only have
one expression. The syntax used is the following:
20. ARRAYS
Proper arrays are in the NumPy library. Here they only talk about lists.
After this letter we can use the 't' for text and the 'b' for binary (mostly
for images), the former being the default one. We give a variable the value for the
file.
To know exactly where we are searching the documents we can use '!ls'.
We have already seen how to create files in the the file handling.
To delete a file we must import the 'os' module and use the function
'os.remove(file)'. We can check if the file exists with the command
'os.path.exists(file)'. We can also delete empty folders with 'os.rmdir'.
25. BUILT-IN FUNCTIONS
25.2. Enumerate
25.3. Filter
25.4. Input
25.6. Operations
25.7. Reverse
25.8. Round
25.7. Sort
25.8. Zip
We use markdown cells to write text in the notebooks. We can use markdown, a
system to format text using raw text only. Also, LaTex and HTML are supported. I
will not see the latter.
- *italic text*
- **bold text**
- `line of code`
- [link](url)
- 
- Table formatting:
| col1 | col2 |
|------|------|
| y | n |
| y | y |
| n | n |
- # Title
- ## Subtitle
- ### Subsubtitle
- Code:
```python
# Python code
list = [0, 1, 2, 3]
for i in list:
print(i)
```
- > Quotation
- $$ LaTex $$
27. COMPREHENSION
We can build collections with one line of code, called comprehension syntax.
We can use loops, nested loops and conditions.
28. CLASSES
28.1. Creation
class MyClass:
x = 5
We would create an object with 'p1 = MyClass()' and would get the value
of x with 'p1.x'.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
28.3. Methods
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
29. INHERITANCE
28.1. Definition
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
This adds the __init__() function, and keeps the inheritance of the
parent class. Functionality in the __init__() function can now be added.
Python also has a super() function that will make the child class
inherit all the methods and properties from its parent:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
By using the super() function, you do not have to use the name of the
parent element, it will automatically inherit the methods and properties from its
parent.
28.5. Methods
So, modifying the new init function we can have different properties
than the ones of the parent class, but we preserve the methods. We can now also add
other ones.