Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 17

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

The 'print('')' command is to write plain text as outcome.

2. SYNTAX

Indentation is mandatory because it indicates a block of code.

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

We create variables by assigning them a value at the start. We don't


have to declare them and they can have different types. Some examples are 'x=5' and
'y='Hello world''.

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.

4.2. Variable names

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'.

4.3. Multiple variables

We can assign multiple variables in one line or one value for different
variables.

x, y, z = 'Orange', 'Banana', 'Cherry'


x, y, z = 'Orange'

We can also extract the variables from lists, tuples and others.

fruits = ["apple", "banana", "cherry"]


x, y, z = fruits

4.4. Output variables

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.

4.5. Global variables

Variables created outside of a function will be global variables, which


means they an be used everywhere. If we create a variable inside a function with
the same name as a global variable, the latter will remain unmodified and the
function will make use of the local one.

To create a global variable inside a function we use:

global x
x = 3

5. DATA TYPES

Different data types can do different things.

Text Type: str


Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType
The 'type()' function will tell us the type of the variable.

x = "Hello World" str


x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None

But they can also be specified.

x = str("Hello World") str


x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = range(6) range
x = dict(name="John", age=36) dict
x = set(("apple", "banana", "cherry")) set
x = frozenset(("apple", "banana", "cherry")) frozenset
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview

6. NUMBERS

6.1. Integer

They are whole numbers.

6.2. Floating point

They contain decimals. In them, e indicates power of ten: 1.35e5.

6.3. Complex

Their imaginary part is written with a 'j': 3+5j.

6.4. Conversion

You can convert integers and floats to all the other types.

6.5. Random numbers

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 have to know some things when we change the type of a variable.

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 can be created with single or double quotation marks. A multiline


string is obtained with the triple quotation marks.

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()'.

The keyword 'in' allows us to check is a string is present inside


another one and it returns a boolean. The keyword 'not in' helps us check the
opposite, if it is not there.

8.2. Slicing

We can return a range of characters from a string with the slice


syntax. We use [start:end] where the end is not included. If we leave a blank they
will work from the start and until the end of the string. Using negative numbers
allows us to start from the end of the string. The most complete syntax is
'[i,j,n]' returning the elements 'i+p*n' until we arrive to j with p all natural
numbers (containing 0).

8.3. Modify

There are some functions that allow us to modify strings:


- .upper(): returns in upper case.
- .lower(): returns in lower case.
- .strip(): removes the spaces and invisible characters in the
beggining and in the end of the string, not the ones in the middle.
- .replace(string1,string2): replaces the first string for the second,
differenciating between upper and lower case.
- .split(separator): splits the string into substrings based on the
separator, which is a string. Returns a list.

8.4. Concatenate

We can concatenate strings with the '+' operator. We can concatenate


the same string several times by multiplying it for the number of times as an
integer.

8.5. Format

We cannot combine strings and numbers in a sole variable. We use


formatting to print this kind of things. We always put placeholders '{}' where we
want our numerical variables to be printed. We use 'string.format(variables)'.
There can be unlimited number of variables to be printed, which must correspond to
the number of placeholders. We can put an index number inside the placeholders
corresponding to the order they appear inside the format function to make sure that
the correct variable is printed in each one of them. To specify the number of
decimal places, we write after the variable ':.2f' (2 decimals in this case).

We can also use the f-string, in which the syntax is


'print(f'x={x}'')'.

8.6. Escape characters

To insert illegal characters inside a string we just use backslash '\'


before the character.

8.7. Methods

There are lots of functions we can use on strings. Some interesting


are:
- .count(string): returns the number of times a specified value occurs
in a string.
- .find(string) or .index(string): searches the string for a specified
value and returns the position of where it was found.

8.8. String to time object conversion

From a string like '01/01/2017 11:00', we can set it to a date variable


using the following module.

import datetime
string = '01/01/2017 11:00'
date = datetime.datetime.strptime(string, '%d/%m/%Y %H:%M')

9. BOOLEANS

Booleans can have two values: true or false.

We can use this to evaluate any expression, such as a comparison between two
values with '<', '>' and '=='.

We implicitly use this in if statements where the condition is really a


boolean.

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:

- Arithmetic operators: addition '+', substraction '-', multiplication'*',


division '/', modulus '%' (gives the residu), exponentiation '**' and floor
division '//' (low integer result, gives the quocient).
- Assignment operators: '=', all the arithmetic but followed by equal sign
will perform the operation on the variable with the selected value. An example is
'x += 3'. There are other ones that I do not understand.
- Comparison operators: equal '==', not equal '!=', greater than '>', less
than '<', greater than or equal to '>=' and less than or equal to '<='.
- Logical operators: 'and' returns true if both statements are true, 'or'
does so if at least one of them is true and 'not' reverses the value of the
boolean.
- Identity operators: 'is' returns true if the objects are the same and 'is
not' does the opposite. Recall that they have to be the same object, not only have
the same content.
- Membership operators: 'in' returns true if a certain sequence is present in
an object and 'not in' does the opposite.
- Bitwise operators: '&' AND sets bits to 1 if they are all 1, '|' OR sets
them to 1 if one of them is 1, '^' XOR sets them to 1 if only one is 1, '~' NOT
inverses them, '<<' ZERO FILL LEFT SHIFT pushes a zero in the right losing a bit on
the left and '>>' SIGNED RIGHT SHIFT copies the left bit and it pushes them from
the left losing the ones in the right.

The order of preference for the operations are parentheses, exponentiation,


multiplication-division-floordivision-modulus, addition-substraction and others
that are not usually used. If they are the same category we evaluate from the left
to the right.

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 '[]'.

11.1. Access list items

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'.

11.2. Change list items

We can change items by redefining them with the indexing. It can be


done for a simple value or for a range of the list. We can also insert items to the
end with '.insert(index, item)'.

11.3. Add list items

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

There are 4 ways of removing items:


- .remove(item): will remove the first item that coincides.
- .pop(index): understandable.
- 'del' function allows to remove a list or only a part of it. The
syntax is 'del list[]'.
- .clear(): empties de list.

11.5. Loop lists

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.

11.6. List comprehension

It is a shorter syntax that allows us to work with lists faster. It can


be done to do several things, like just doing for loops in one code line. It can
also be used to create new lists. The syntax for the latter is stated after, and
will add the items of the previous list to the new list if the condition is true.
The expression can be a manipulated form of the item and the list can be, in fact,
any type of iterable. Finally, we can use a condition 'if' IN THE EXPRESSION, not
to create a filter to decide if the expression is going to the new list (which is
done at the end), but to modify it as we want before adding it.

'newlist = [expression for item in list if condition == True]'

11.7. Sort lists

We can use the function '.sort(reverse=False, key=function)' to sort


the list alphanumerically with true reverse if we want a descending order. The key
allows us to sort the items based on some other condition: the function manipulates
each item and sorts them with the result of the manipulation. Capital letters will
have priority to sort a list unless we use a key such as 'key=str.lower'. The
function '.reverse()' will reverse the order of the list.

11.8. Copy lists

Copying a list with 'list2 = list1' isnot effective, because this is


just a reference and a change in one of them will affect both. So we use the built-
in function '.copy()' or the built-in function 'list(oldlist)'. There is also the
'copy.copy(list)' from the 'copy' package (import copy). If we have nested lists,
this will not work anymore so we will have to use the 'copy.deepcopy(list)'
function.

11.9. Join lists

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.

11.10. List methods

Two methods not mentioned earlier are functions 'count(item)', which


counts the number of elements with the specified value and '.index()', which gets
the index of a specified value, only for the first one of the list.

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.

12.1. Access tuples

It works exactly as the lists.

12.2. Update tuples

A priori, tuples are immutable, but there is a workaround: overwriting


them. We can convert the tuple to a list, change it and then overwrite the tuple
variable. We can also add items by adding tuples, which is allowed.

12.3. Unpack tuples

We can extract the values into variables (called unpacking) by putting


the name of the new variables which will store the values between '()' and
separated by commas. If the number of variables are unmatched, they will
automatically be matched (always with the number of variables being lower than or
equal to the number of values) putting an asterisk '*' before the variable that we
want to be a list of the remaining items.

12.4. Loop tuples

They work as in lists.

12.5. Join tuples

They can be concatenated with the addition and also multiplied by a


number to concatenate it that amount of times.

12.6. Tuples methods

We only have '.count()' and '.index()' which work as in with 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.

13.1. Access set items

We cannot search for them with indexing so we have to loop through them
or search with the 'in' function.

13.2. Add set items

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.

13.3. Remove set items


We can use the '.remove(item)' or '.discard(item)' to remove an item,
with the difference that the latter will not raise an error if the item is not in
the set. The '.pop()' function will remove and store in the new variable a random
item from the set. We can also use the '.clear()' and the 'del' functions as with
lists.

13.4. Loop sets

They work as in lists.

13.5. Join sets

We can use the aforementioned '.update(set)' function to modify an


existing set or the 'set1.union(set2)' to create a new set. If we only want to keep
the duplicates we use '.intersection_update(set)' or simply '.intersection()' if we
are creating a new set. We can get the elements not present in both sets with
'.symmetric_difference_update(set)' or simply '.symmetric_difference(set)' if we
are creating a new set. Again, 'True' and '1' are the same value.

13.6. Set methods

Already seen the most important ones.

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,)'

14.1. Access items

As said, an specific value can be accessed with indexing of the keys


but also with the function '.get(key)'.

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.

Finally, we can check if a key exists using the keyword 'in'.

14.2. Change items

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.

14.3. Add items

We use exactly the same method as for changing items. Simply, if they
do not exist, they will be created.

14.4. Remove items


We can use the function '.pop(key)' to get rid of an specific item of
the dictionary or '.popitem()' to remove the last one inserted (or a random if we
are in Python 3.6 or less). The function 'del' followed by the indexing with the
key of the item we want to remove will eliminate the item, but followed simply by
the name of the dictionary will erase the latter. The '.clear()' function will
empty a dictionary.

14.5. Loop dictionaries

When looping in dictionaries, the returned values will be the keys.


Here the functions to access items '.keys()', '.values()' and '.items()' are more
useful, because they are iterables. For the last function, we have to put values
and keys in two different variables.

14.6. Copy dictionaries

An equal sign to a dictionary will only be a reference, so they will be


the same object. Copies can be made with '.copy()' or construction with
'dict(dict)'.

14.7. Nested dictionaries

We can have dictionaries inside other dictionaries. To construct them,


we open a dictionary and we write the syntax 'dict1:{}' and the different
dictionaries separated by commas. We access the items by indexing twice, one
followed by the other.

14.8. Dictionary methods

We can use the funtion 'dict.fromkeys(iterable of keys, value)' to


create a ditcionary with different keys with the same value.

They can be sorted using the 'sorted(collection, key=function)'


function. The collection is the 'dictionary.items()' and function is the defined
function that returns the thing used to order them. It will return an 'items'
dictionary object. To get into a dictionary again, it depends on the Python version
we have:

- Python 2.6 or before:

from collections import OrderedDict


newdict = OrderedDict(dict_items)

- Python 3 or newer:

newdict = {k: v for k, v in dict_items}

Python version can be checked with

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.

Another case would be conditional expressions for if and else statements,


where we indicate the action first followed by the if statement and one or multiple
else with the other actions possible. In this case, we don't use 'elif' but instead
we use 'else+action+if+condition' for different conditions than the first one, and
we can finish with a simple 'else' that will actually work as an 'else'.

We can also use logical operators to play with different conditions in the if
statement: 'and', 'or' and 'not' are the options we have.

Finally, we can have if statements inside other if statements, which we call


nested if statements.

We can have an if statement that does nothing, but we cannot leave it empty,
we write instead the keyword 'pass' inside it.

16. WHILE LOOPS

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.

17. FOR LOOPS

This loop allows us to iterate along a sequence (an iterable or a string). We


can execute a set of statements for each item in the sequence and does not require
an index variable. Strings have sequence of characters, and iterables of items or
pairs in the case of the dictionary.

The statements 'break' and 'continue' work as in the while loops, as well as
the 'else'.

It is very useful to get an iteration a certain value of times with the


combination of a for loop with the function 'range()'.

We can also use nested for loops and the pass statement as before.

18. FUNCTIONS

18.1. Creation of a function and utility

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.

If we want it to use parameters, we have to put them inside the


parenthesis and separated with commas. The difference between parameter and
argument is that the parameter is the variable when the function is defined and
argument is the variable when the function is called.

18.2. Multiple arguments

Generally, the number of arguments must coincide with the number of


parameters. We can give the different parameters as a list and Python will unpack
them if we use '*' before the argument when we call the function.

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.

We also can have an arbitrary amount of keyword arguments, so we add


'**' in front of the parameter name and we index it with the key when we want to
use it (or if it fits the number of variables it will adjust the values of the
dictionary to the variables), given that the arguments have been transformed to a
dictionary.

As a note, arbitrary arguments are '*args', keyword arguments are


'kwargs' and arbitrary keyword arguments are '**kwargs'.

18.3. Return and other properties

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.

If we want to return a value we use the 'return' statement followed by


what we want it to return.

The 'pass' statement can also be used here.

Functions in Python accept recursion, which means that they can call
themselves. This allows to loop through data to get a result.

They can be documented with a docstring, a block of text written just


after the definition of a function with '''content'''.

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:

'x = lambda arguments : operation' where the arguments, if plural, are


separated by commas.

It is useful to have an anonymous function inside a real function. An example


is when we create a function that takes one argument and multiplies that value with
an unknown number. We can use the 'lambda' function in the return code line, create
different functions that will multiply the argument by a desired number by calling
the function and storing this in a variable and finally calling this variable with
the number we want to multiply.

20. ARRAYS

Proper arrays are in the NumPy library. Here they only talk about lists.

21. FILE HANDLING

Python allows to manage files.

The most paramount function is 'open(file,mode)', where 'file' is just the


name of the file and its location and 'mode' can be:
- 'r': opens the file for reading and it is the default value. The file must
exist.
- 'a': opens the file for appending. Will create the file if it does not
exist.
- 'w': opens the file for writing. Will crete the file if it does not exist.
- 'x': creates a file. There cannot be a file with that name previously.

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.

Remember to close the files with '.close()' after using it.

A CSV file is a file in which the information is separated by commas.

To know exactly where we are searching the documents we can use '!ls'.

22. READ FILES

Once a file has been opened in the reading mode we can:


- Read all the file with '.read()' or read only some characters in the file
by specifying inside the parenthesis the number of charaters desired.
- Read a line with '.readline()'. If we call it again, we will print the next
line. If we use a loop with the file, we will loop across the lines of the file, at
the point where we had read the last one.

23. WRITE/CREATE FILES

We can write with the '.write(text)' in two different ways:


- With the 'a' mode, which will append the text at the end of the file.
- With the 'w' mode, which will overwrite the content.

We have already seen how to create files in the the file handling.

24. DELETE FILES

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.1. Complex numbers

We can create complex numbers with the function


'complex(real,imaginary)' or 'complex(string)' where the imaginary part is denoted
with a 'j' afterwards.

25.2. Enumerate

The 'enumerate(iterable)' function takes an iterable and returns an


object with tuples containing a pair with an index and a value. We can then
transform it into a list or just loop in it. It is useful because if we new a
counter we can do it with this function instead of initializing the counter and
therefore writing more amount of code.

25.3. Filter

We can filter a list by creating a function with the desired condition


and that returns a boolean according to it. The we use the function
'filter(function,list)'.

25.4. Input

We can ask for an input to be written with 'input(message)' by storing


it in a variable. It will be a string.

25.5. Max and min

To get the maximum or minimum value from an iterable, we use the


'max(iterable)' or 'max(item1,item2,...)' to get the biggest numerical value or by
alphabetical order if they are strings. The 'min()' function is analogous.

25.6. Operations

Some built-in operations are the power function 'pow(x,y)' which is x


to the power of y and the sum of the content of an iterable 'sum(iterable)'.

25.7. Reverse

We can reverse an iterable with the function 'reversed(iterable)'.

25.8. Round

We can round a float to a certain number of decimals with


'round(number,digits)'.

25.7. Sort

We can sort an iterable with the function 'sorted(iterable)'. We can


sort it in descending order with 'reverse=True'.

25.8. Zip

A very useful function is the 'zip(iterable1, iterable2, ...)'


function. It will pair the values of the different iterables in tuples inside an
iterator. It is useful to associate variables stored in different collections. The
minimum lenght is taken if they are not all equally long.
26. TEXT

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.

Markdown syntax is the following:

- *italic text*
- **bold text**
- `line of code`
- [link](url)
- ![name](image.jpg)
- 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

Python is an object oriented programming language. Almost everything in


Python is an object, with its properties and methods. A Class is like an object
constructor, or a "blueprint" for creating objects.

We create a class with:

class MyClass:
x = 5

We would create an object with 'p1 = MyClass()' and would get the value
of x with 'p1.x'.

28.2. Init function


We also have the '__init__()' function. It is always executed when the
class is being initiated and it can be used to assign values to object properties,
or other operations that are necessary to do when the object is being created. An
example:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)

28.3. Methods

These are functions that belong to the object. Example:

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

Inheritance allows us to define a class that inherits all the methods


and properties from another class. Parent class is the class being inherited from,
also called base class. Child class is the class that inherits from another class,
also called derived class.

28.2. Parent class

They are created like a normal class.

28.3. Child class

To create a class that inherits the functionality from another class,


send the parent class as a parameter when creating the child class. We can use pass
inside the class if we want it to work exactly the same as the other one. The
properties and methods will be the same. When you add the __init__() function, the
child class will no longer inherit the parent's __init__() function. It overrides
the one from the parent class. It is done by:

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.

28.4. Super function

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.

You might also like