0% found this document useful (0 votes)
3 views61 pages

Programación Python para Principiantes - Parte4

The document explains various Python functions such as type(), list(), str(), and others, detailing their usage and expected outputs. It also covers the rules for defining functions, the importance of parameters, and the distinction between local and global variables. Additionally, it introduces modules in Python, highlighting their benefits for code organization and reusability, along with instructions for creating and importing modules.

Uploaded by

jestevezviveros
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views61 pages

Programación Python para Principiantes - Parte4

The document explains various Python functions such as type(), list(), str(), and others, detailing their usage and expected outputs. It also covers the rules for defining functions, the importance of parameters, and the distinction between local and global variables. Additionally, it introduces modules in Python, highlighting their benefits for code organization and reusability, along with instructions for creating and importing modules.

Uploaded by

jestevezviveros
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Type() function: This function will X= 14; Y=(“Hello”)

notify the type of data of the Print(type(X)); print (type(Y))


element we put on it. Will print: “int”; “str”
List() function: This function will Word=list(“Book”)
create a list, using and argument Print(Word)
on specific Will print: “B”, “o”, “o”, “k”.
Str() function: This function will X=14 ( A Number)
convert any integer data type into A=str(X). print(A)
a string data type Will print: 14 (A String)
Range() function: This function X= range(5)
will create a list of elements, Print(X)
determined by the programmer. Will print: 0, 1, 2, 3, 4.
This function is usually used in
for cycles
Float() function: This function X=float(“3.14”)
will convert any value into a Print(X)
decimal type value (Float) Will print: 3.14
Min() and max() function: This X=[15, 4500, 200]
functions will return the minimal Print(min(X)); print(max(X))
and maximum value in an array of Will print: 15; 4500
numbers
Sum() function: This function will Y= [10, 6, 9]
add all the numbers in an array Print(sum(Y))
Will print: 25
Int() function: This function will X=int(“19”)
convert any data type into an Print(X)
integer Will print: 19
Len() function: This function will Len(“I am a programmer”)
determinate the length of the Will return: 17
characters contained on a string.
Round() function: This function Print(round(13.56))
will round all the decimals Will print: 14
numbers to its closest integer

Rules to follow to define properly a function:

• The code that goes with the function will always start after the “:”
character.
• It is really important to identify correctly our code and be very careful
with its indentation (four spaces).
• The parameters that go with the function must be defined inside the
parenthesis of the same.

A function will never be executed unless it is invoked, and this is nothing


more than calling it by its name:
As we can see in this example, this is a way to define a function. Obviously,
this function won’t do anything, because it is just a demonstration of how
the syntax is and how to call or invoke it. As you could see, we used the
reserved word def, to then define the function. Then, inside the parenthesis,
we have arguments or parameters of the function, which come to be the
inputs, and lastly, the sentences and statements that define what our
function will do.

After defining our function, we can call it whenever we want to.

How Can I Create My Own Function?


As we mentioned earlier, Python allows us to create functions; for that, we
only have to make use of the def statement. After this, we will name it as
we want (It is strongly recommended to use a name that is related to the
program to avoid confusion).

Once created, how can I make use of it? In order to be able to call or use a
function, all we have to do is to declare it at the beginning of our code. This
is really important since if this is not done, the Python interpreter won’t be
able to identify it, so the function will not exist and will not work.
Parameters
We call parameters to all those values that are going to be used in a
function; they will work as inputs. Functions can receive one or more
parameters and they just have to be written correctly and separated by a
comma, in order to be invoked.

For example:

With this, you could see how easy it is to define the beginning of a function.
It is really, REALLY, important the use of the def word, since this is the one
that will tell the Python interpreter that a function is being created.

Afterward, we name our function. In this case, we named it firstfunct. On it,


we could observe that there are parenthesis around x and y, meaning that
those are going to be the parameters that our function will use as inputs to
work properly.

What are the arguments or parameters?

As we already know, the parameters are the values that the function is going
to receive when it is defined. These values are going to be called arguments,
and are classified as follows:
• Argument by position: When we send an argument to a function, this
one receives it in an ordinated way, which was defined previously.

In this example, you can see that a function named “Hello” was created; its
parameters are name and age. We have created this function to print a
message on the screen saying the name and age that the user writes.

We also defined the variables x and y, which are strings that are related to
the name and the age. It is important to do this because otherwise, the
function will not be able to run.

Finally, we called the function “Hello”, and we have put the arguments on a
specific order so that the message that will be print on the screen makes
sense. If we had written “Hello (y,x)”, the message print on screen would
have been like this:
“Hello 16, I am Matt years old”.

• Arguments by name: When we call a function, it should have


identified on its arguments the value that each parameter will have
according to its name.
You can see that we defined the number function; this will contain the
parameters x and y. After we defined it, we added the sentence return and
right after it a subtraction.

Later, we created the variable c, which will have the value of the return. To
call this function, all we have to do is to write its name next to the values
that it will have inside the parenthesis.

ERROR: Not enough arguments: This error happens when we call a


function with defined parameters that are not present or written correctly.

Here, we will show you an example of a function that has no parameters.

As you could see, the function number() has no input parameters, hence,
what it will do, is to simply print the message number().

Return Statement
Until this point of the book, you may have noticed that Python’s functions,
on its majority, have return values, which can be explicit or implicit. We
also know that the return statement is a keyword of Python; its purpose is to
end the execution of a function in order to obtain a result value of it.

Lambda Function
We define a lambda function as a special function, this one is part of the
default functions of the Python programming language, and it is an
exclusive function.

What do we mean when we say that it is an exclusive function?

The lambda function has a special syntax and that is the reason why we
consider it an exclusive function since it allows us to create any kind of
function on a really fast way, without having to save it.

It is also capable of executing an expression and automatically return its


result, this could also have some optional parameters on its structure, but
the restrictions of this lambda function must always be respected.

Its syntax is really easy and simple, you only have to write the reserved
word lambda, the arguments and finally the “:” character, like this:
You can easily see the use of the lambda function. We have a sum function
that we equaled to lambda, who is going to have two parameters, a and b,
which are going to be added. Additionally, we have the x parameter, which
will store the respective values of a and b in order to do the add.

The lambda function is used mostly to call functions that are needed in a
program for a really short time, since, as it would be used so quickly and so
little, naming it is not necessary. This function is commonly used with the
filter() and map() functions.

Filter() Function
We define the filter() function as the one that has the task of filtering
arguments, whether they are lists or iterators. As a result, this will always
return an iterable with the elements that have already been filtered.

In this example, we will show you how it works. This will filter the people
that will be able to enter a local for +18 people. We will define then, the
filter() function and the iterable.
So, you could see how we created a list of the different ages of the people
that want to go to the local. Then, we created the function passfilt, which
will filter the data that is given, returning whether True or False. The next
sentence will create a list with the people that approved the filter.

Lastly, we created a for loop, which will show us on the screen the obtained
results, telling the user which ages were allowed.

Map() Function
This function will execute elements on a tuple or a list, in order to be able to
return elements on the sequence, as the result of the operations. This
function is used mostly to simplify the code and make it simpler, avoiding
the creation of unnecessary loops or other resources.

In this example, you could observe that, at first, we defined the sum()
function, which returns a+b. Then, we created the list1 and list2 lists, which
has integers on it, put there as items. Later we created the result variable,
which will have the value of the result of the map function. That value will
be the addition of the items one by one of both lists. Then we used the list()
function to convert that result into a list.

The second example, on the same image, was pretty much like the first one.
The only difference is that instead of using integers, we used strings, and
instead of adding, the function concatenates those strings. Finally, we used
again the list() function in order to get a list as a result.

What Is the Difference Between Def and Lambda?


As you may have noticed, creating a function with the def statement is the
same as creating it with lambda since, in both cases, we will get the same
result, and the difference is that the objective is reached in two different
ways.

Sometimes, to get somewhere, we will find two different ways, one shorter
and simpler and the other longer and harder; that is what happens here.
Lambda would be the easy way since it allows us to use functions easily on
our code.

When we create a lambda type function, this will be focused on a single


line of code, reducing then the total line count of our program, while when
using def, we have to define it in more than a single line.

At the moment of using the lambda keyword, we create an object or


function which will not have to be defined with a name, unlike it happens
with def, that has to be defined at the beginning of our code to be able to
use it.

Despite being the lambda function better for saving lines of code,
sometimes the def statement is easier to understand for those users that are
getting started into programmers and even for those that already have some
experience but not that much.

It is important when operating with a lambda function type, to assign a


variable to it, since, if this is not done, it will only operate on the line on
which it is defined.
Variables
As you might know, variables are those that store information, they can
store different data types such as integers, floats, strings and they can be
renamed and changed during your program and code by using the
statements that you think are needed. Those variables will work on the main
program. If you know a bit about the C programming language, those
variables will be stored on the Main. But there are other types of variables,
which can be very useful when it comes to programming.

Global Variables
These variables are really important since they will always be the same, no
matter where on the code they are located. They will always have the same
value and we will be able to use them all through the code.

A recommendation we can say about its use is that you must be really
careful because you can make mistakes very easily.
As you can see in the example, we declared the variable vari as a global
variable, hence we can access them anywhere in the code.

Then, we defined the function sum, who will have as a parameter a and will
return the add of the global variable vari plus the parameter entered on the
function.

At last, vari will be equal to the sum of vari plus seven, in this case, vari
would be seven, then vari would be equal to the of vari plus fifteen, and it
will be equal to twenty-two.

Local Variables
This is another type of variable, which is very useful because they only
exist inside a piece of a block of the program. After the block is ended, the
variable is deleted. This type of variable is good and recommended when it
comes to don’t wasting memory. Here is an example:

You can see that here, we defined the sum() function, which has two
parameters, a and b. The next thing that was done was to create the result
local variable that is equal to the sum of the parameters. Later, the local
variable f is created, who is equal to the string “HI”, and lastly, we ask the
program to return the result variable.

After creating the function, we say that the variable a would be equal to the
result of sum (1,3); then a would be equal to 4.

You might be wondering why we created the f variable. It is a local


variable, so it does nothing outside the function we defined as def, so it
doesn't affect the behavior of the code
Chapter 6: Modules

A module is defined as an object of Python, which has certain attributes, to


which we can give an arbitrary name and also link them. A module allows
us to organize the code, to make easier the understanding and use of our
code to third party people and even to ourselves.

In other words, we can define a module as a simple file with a .py extension
that is capable of defining functions, variables, classes and also include
executable code.

Why Should You Use Modules?


Modules allow us to organize the elements and components inside our
codes in an easier way, providing us with a big package of variables that are
auto contained. Names that are defined on a superior level in a module file
automatically will become an attribute of the object of the imported
module.

Another advantage of using modules is that they let us reuse the code, using
data services and linking individual files to broaden our program.

The main reason why we think that the modules are a very useful tool when
it comes to programming is that they are really helpful to organize and
reuse our code. This is very important when we talk about OOP (Object-
Oriented Programming) since on that mode, the modularization and reusage
are very popular. Since Python is a programming language oriented for that,
it comes very user-friendly.

Imagine that you want to create an application or a program, more complex


than what we have been doing until now. For it, you are going to need one
of the previous codes to complement. Here is when you see the real benefit
of the modules since you will be able to simply add one of the old codes to
the complex application you want to do.

In modules, we will also have modularization. It is based on dividing our


codes into several tiny pieces of codes, so that, at the moment of making the
complex program or application, it won’t have hundreds and hundreds of
lines of codes that could be annoying and hard to read. Instead, the code
will be separated into tiny files.

How Do We Create a Module on Python?


Creating a module is something very easy that anyone can do, all that needs
to be done is to create a file with the .py extension, then, that file will be
stored on a folder of your preference; this is known as import.

Python, on its default library, has a big amount of modules, we can observe
them on the official manual. You can find it on the following link:
[Link]

In case we want to create a module of our own, you will have to do the
following. We will make a program on which we will create a module that
could be used later.

The module syntax is as follows:

As you could see, the syntax is really simple, since it is pretty much like
creating a function. After we created it, we must be able to import it from
another program, in order to do that, we will use the import statement.

Import Statement
A module is able to contain definitions of a function and even statements,
which can be executable. With this, it is possible to initialize a module since
they execute only when our module is on the import statement.

Modules are capable of importing other modules, that is why people use to
put the import type statements at the beginning of each since with the
names of our imported modules, they will locate on a space named global;
function that modules have for importing.

With the help of the last example, we can manage to import the module
created previously and use the functions that we defined there.

As you see in this example, we created the op variable, who takes the task
of storing a string, which will specify the option that the users choose.
Then, two variables would be initialized, a and b; they will store the value
of the operators we are going to use to perform the mathematical
operations.

Afterward, the result variable will store the value that the function
calculator returns, according to the operators and the type of operation that
the users want. The function calculator comes from the module that we
have imported.

When the Python interpreter finds the import statement, it imports the
module, as long as it is located on the full search path. The search path is
nothing but a list where all the directories that Python accesses before
importing any module are located.
How to Import a Module?
For being able to import a module, we just have to follow some instructions
and steps that are performed at the moment of the execution:

We look for the module through the module search path, compile to byte
code, and lastly, we execute the byte-code of our module to then build an
object that defines it.

How can I search for a module through Search Path?

To search for a module, our search system compounds of the concatenation


of paths; these can be seen on the directory “Home” of our program. After
this, the environment PYTHONPATH will be located from left to right, and
that is how we will find the directory of default libraries.

Namespaces in Modules
As you know, modules are files. Python creates a module object in which
all the names that we assigned in that module-file will be contained. What
does that mean? This means that namespaces are just places where all the
names that later become attributes are created.

What Are the Attributes?


Attributes are the names that have been assigned to a value considered of a
higher level on a module file, which does not belong to
a function or class.
Chapter 7: OOP (Object-Oriented Programming)

Object-oriented programming is a form of programming in which we can


observe in a more real way than the things that occur to us at the time of
programming. This is a paradigm, which refers to theories, models and
methods that allow us to solve more quickly and efficiently any problem
that may arise.

As its name implies, object-oriented programming is based on the object


model, where the object itself is the main element that will contain all its
characteristics and behavior, making it independent, but at the same time
relating it to elements of a class.

This type of programming differs from structured programming since its


main objective is that through some input data, produce an output.

Some of the benefits of working with OOP are:


We can maintain a certain uniformity in the code.
It allows the reuse of code, since it allows us, after having created an object,
to use that same definition, to create other objects.
It is a good practice when it comes to programs, not to say that it is one of
the big pros of Python.

As we have seen before, object-oriented programming is a way of


programming based on finding a solution to problems. This type of
programming introduces new concepts, which complement and even
overcome those we already know. But first, we should ask ourselves:
What Is a Class?
It is the way we can begin to create our own objects, since from there, we
can add to each class its attributes that are nothing more than that class and
its methods, which are something like the actions that the class can perform.

A clear example, to understand this, is that we have the computer class,


which can have a mark, a color, a Ram memory, a ROM memory, a
processor, among other things, being these the attributes of our class, then
there are the actions that computers can do, such as navigate, turn on, turn
off, sound, among others, being this the methods of our class.
In order to create a class, in this case, that of computers, let's see the
following example:

As we can see in this example, we created the PC class, the brand is Dell,
has 4 Gb of ram, 512 Gb of ROM and an intel i5 processor; this is the way
we can create a class that only has attributes, but to make use of this class,
we need to create an object, which will be explained below.

Object characteristics:
• Object: An object is an instance of a class, this entity is the result of a
set of properties, attributes, behavior or functionalities in which they
react to events that occur in the program.

• Method: A method is a type of algorithm, which will be related to an


object or its class itself. The execution of an algorithm is triggered
after receiving a message which indicates what an object can do, and
even the method itself can generate changes between its properties.

• Message: We define a message as the direct communication to the


object, this one is going to order itself to execute some of its methods
with the parameters that it contains associated, according to be the
event that generates it.

• Behavior: This will be defined by the messages or methods to which


the object will know how to respond. What do we mean by this? This
is nothing more than saying that the behavior will be the operations
that can be performed with the object.

• Event: We define an event as an event that occurs in our program,


either interaction of the user with the computer or a message sent by
an object. Our program takes control of the event through a message
to the target. How is this? In a few words, we can say that an event is
a reaction that triggers the behavior of an object.

• Attributes: We define an attribute as the characteristic that a class is


going to have.
• Components of an object: Objects are made up of attributes, identity,
relationship and methods.

• Identification of an object: an object is identified through a table that


is going to be composed by the attributes and functions that
correspond to it.

After having explained some characteristics of the objects, we can create


our first object, in this case, our first computer:

As we could see in this example, specifically in the past one, we created the
class, as we did previously, then we created our first object, with the myPC
name, which is of the PC type. To verify that the ram of our computer is
four gigabytes of ram, we use the dot property.

This property is used to access the attributes of our objects, and this is done
by placing a dot, as previously seen, and then write some attribute of the
object.
But this sounds a little repetitive since it seems that all computers are the
same, but Python had already thought about this, for it, there are
constructors so that we can make objects as the user wants and not in a
predetermined way. In the following example, we are going to place
constructors and methods in the same example, with the objective of
making a complete example so that it is clear to the readers:

In this example, we can see how to create a class, since it has its respective
constructor, which uses the reserved word self, which is used to access an
attribute from any method without any inconvenience, also to observe how
the other modules were created, you could realize that they have been
created using as arguments the word self, no matter what method it is, that
word should always be there, and also, every time you want to access an
attribute within the class, it is necessary to use the word self, you could also
see how we added the behavior of turning the computer on and off.

The next act was to create an object called myNewPC, which is class PC,
and also has the characteristics, whose brand is Acer, has 8 Gb of ram, 1 Tb
of ROM and has an AMD processor. The next act was to turn on the pc,
using the turnOn() method, using the methodology of the dot, and finally,
we want to know which processor has our new computer, also using the
nomenclature of the dot.

Already seeing the potentiality that this object-oriented programming has,


we will be able to observe some very important properties of them:

Abstraction: They enhance the most significant characteristics of each


object in an analog way that captures the behavior of it. These objects
present a degree of abstraction since they allow to communicate with other
objects of the same class even without needing to show their characteristics.
Therefore, abstraction refers to an object being able to isolate itself from all
others and only concentrate on its tasks.

Encapsulation: This is based on bringing together all the elements that are
considered of the same essence that contains the same level of abstraction
in order to make a better design of the structure of the components of the
system.

Polymorphism: It is about the different methods or better said, behaviors


associated with different objects that have the same name, because when the
method is called, it will perform the behavior corresponding to the object
that is required; an example of this, can be that a car is going to start, being
this the method, then we also have that a motorcycle can start, being this a
method of this class too.

Modularity: It responsible of dividing the program or the application in


several stages, in this case, the modules; you can imagine it as an old
equipment of diskettes, that the modules acted independently, where each
one becomes independent modules of the others, allowing this way to run
separately, but even so, these have connections with the other modules, but
they do not depend on others to run, but that they could use the data of the
other pieces of code.

Inheritance: This characteristic is very important, since it relates to several


classes, so that they relate between them, generating a type of hierarchy, so
to speak, the objects that have less hierarchy are going to inherit properties
and attributes of the classes that have a greater hierarchy. In this way,
polymorphism and encapsulation can be organized and facilitated, thus
allowing objects with a smaller hierarchy to be created and defined as more
specialized objects of the higher classes. Therefore, a small example could
be that a computer being a fathering class, and a daughter could be a
telephone, inheriting all the properties of the father class, with others a little
more specific.

Now, in the case that an object inherits more than one class, this object has
greater complexity, being a very specific instance.

Creating a class daughter: Already knowing the theory, we can see the
following example, where we create a cell class because as we all know all
modern cell phones are computers, but not all computers are cell phones, so
let's see the following example:

As we could see in this example, a PC class is created, which we have seen


previously how it was created, then we create the class daughter of PC, it
has a constructor and has as inputs, all the arguments of the father class,
plus the arguments signal and battery; then to initialize the constructor, we
call the method of the father class __init__(), and then we will initialize the
other two attributes as it is normally done, assigning to it the value of
[Link] and [Link], the corresponding values.

It also creates a call() method for the phone to call, and this method will
show a message which will say that the phone is calling.
To instantiate a daughter class, what we do is to write a variable, which will
be cellphone class, we insert the different arguments, such as Huawei brand,
ARM processor, among other features. Then we will call the call() method
so that our cellphone calls and finally we want to visualize which is the
brand of our phone, which is Huawei
Chapter 8: File management

One of the advantages of Python is that it allows us to work at two different


file levels: in one, we have the module, which facilitates the handling of
what refers to the system files at the same level of the operating system. In
the second level, we are allowed to manipulate the reading of the files; here
we work reading and writing at the moment of working with the application
since we would be working each file as an object.

When we work with files, these are manipulated in the following way: first,
they are opened, we operate on them, and finally, we close them.

But... What is a Python file? What is meant by this?

We can define Python files as a set of bytes that will contain a certain
composite structure.

Our file will look like this:

File header: These are the data that the file will contain (name, size, type)
of the file we are going to work with.

File Data: This will be the body of the file and will have some content
written by the programmer.
End of file: This sentence is the one that will indicate that the file has
reached its end.

How to Access a File?


There are two ways to access a file, which are very simple, one is using the
file as a text file, where it will proceed line by line, the other way is treating
the file as a binary file, where it will proceed byte by byte.

Open() Function
To open a file in Python, we will use the open() function, and this will take
charge of receiving the name of the file and the way in which the file will
be opened according to its parameters. If you don't enter a file opening
mode, it will automatically open with a default mode, a read file.

It is important to note that the operations to open files are limited, it is not
possible to open a read file when it was opened for its writing, and we
cannot write in a file which was only opened for reading.
There are two types of files in Python, one of them are text files and the
other are plain files, so we must take into account when specifying which
format the file will be opened to avoid any confusion and error in our code.

The open() function is based on only two parameters:


- Enter the path to the file you want to open.
- Enter the mode in which we want to open our file.

The syntax of the open() function is as follows:


Of which the following parameters have the following meaning:

File: This argument will provide us with the name of the file we are going
to access through the open() function, this is what we will call the path of
our file.

The file is considered a fundamental argument because it is the one that


allows us to open the file, it differs from the rest of the arguments because
when some of them can be optional, this one contains some that come from
a predetermined way.

Mode: These will be the modes with which we are going to access and
these are responsible for defining the way in which our file is going to be
opened either for reading, writing, edition.

Next, we have all the ways to access a file:

w: This is the write mode, which will be responsible for opening a file only
for writing; this mode will create a new file in case the file we are working
with does not exist.
w+: This is still the same write mode, but its difference is that it has a plus,
which also allows reading the file.
wb: This is still the same write mode, but its difference is that it opens the
write file in a binary format.
wb+: This is still the same write mode, but its difference is that this file is
opened in a binary format and also allows it to be a read file.
r: This is the read mode, which comes by default when opening any type of
file. This mode will open the file for reading only.
r+: This is still the same read mode, but it has a plus, which allows it to
open a file for reading and writing.
rb: This is the same read mode, which will open a read file in binary format
only.
a: This is the add mode, which is in charge of opening a file to be added.
This file starts being written from the end of the file itself and also takes
charge of creating a new one in case the file we are working with does not
exist.
ab: This mode is still the same as add, but opens in binary format. And it is
in charge of creating a new file in case the file we are working with does
not exist.
a+: This is still the same add mode, but its difference is that the same file
also allows the reading of the file.
ab+: This mode is the same as add, but its difference is that besides being
open in binary, it also allows the reading of the file.

Read a file in Python:


There are three ways to read a file:
1. read([n])
2. readlines()
3. readline([n])
It is important to note that the letter n enclosed between keys and
parentheses will warn the file about the number of bytes that the file must
read and interpret.

Read([ ]) Method

If we want to add a certain amount of bytes to our file, all we have to do is


to write the number of bytes to read inside the parenthesis.

For example, we want to add six bytes; then we write [Link](6)

Readlines() Method
Readlines method is responsible for reading only one line of our file; this
way, he will be able to return in form of a string the bytes he has read. It is
important to mention that this method is not capable of reading more than
one line of code, even if the number “n” of bytes is higher than the bytes on
that line.

Its syntax is very similar to the Read() method.

There are many types of attributes that we will face when opening our files
and those help us to know more about the files.
[Link]: This attribute returns the name of the file which we are going to
work with
[Link]: This attribute returns the ways of access with which we have
opened the file

[Link]: This attribute returns a Boolean. It returns as True, if the file on


which we were working on is closed, and a False if it is still open.

Close() Function
The close() function is the one through which we delete any information
that has been written or stored on the memory of our program; this way, we
can proceed to close a file properly. Even though there are other ways for
closing files, like reassigning an object from a file to another, this function
is the most common.

The syntax of the close() function is the following:

What Is a Buffer?
A buffer is like a temporary file that will contain a fragment of the data
(That composes the files of our operating system) on the ram memory.
Usually, we make use of buffers when we are working with a file whose
storage size is unknown.
If the size of our RAM memory is less than the size of the file that our
program will occupy, the processing unit won’t be able to execute the
program properly.

It is really important to know the size of the buffer since it will indicate the
storage size available at the moment of using our file.

The io.DEFAULT_BUFFER_SIZE function is the one that will show us the


size of our file in a determined program

Errors
When working with files, we will have an optional string. That string will
specify the way about how we will handle the errors of coding that may
arise in our program.

Those errors can only be handled and managed on files .txt

Ignore_errors()= This control statement will ignore the comments that have
a wrong format.
Stric_errors()= This control statement will generate a subclass or an
UnicodeError error type in case that there is any kind of fail, mistake or
error at the code of the file we are working with.

Encoding
Now we'll talk about string encoding, which we often use when we're
working with data storage. But what are data storages? This is just to say
that they are the representation in characters of the coding; your system is
based on bits and bytes in one common character.

The string encoding is expressed in the following way:

Newline
When we talk about the newline mode we refer to the mode that controls
the functionalities of creating a new line, these can be: '\r', " ", none,'\n', and
'\r\n'.

Newline statements are universal, and newlines are universal and can be
seen as a way of interpreting the text sequences of our code.

[Link] end-of-line sentence in UNIX: "\n".


[Link] end-of-line sentence in Windows: "\r\n"?
[Link] end-of-line sentence in Max OS: "\r".

Handling files with the "OS" module


The management of files through the "OS" module gives us many benefits
when performing certain operations that depend on the operating system,
such as starting a process, listing the layers of our files and finalize
processes. To do this, we will rely on a series of methods that make much
easier the tools of file management; these are:

[Link](file_name): The remove(file_name) method of the module will


be in charge of removing a file from the program we are working with.
[Link](): The module [Link]() method will show us the size of
a file in bytes, based on a file that has been previously elapsed.
[Link](current,new): The rename(current, new) method of the module
will take care of renaming the file we are working with.

xlsx Files:
These files are those that allow us to work in spreadsheets as if we were
working in a windows Excel program; if our operating system is windows,
these files will have a much smaller weight to a file of type xlsx in another
operating system.

This type of file is very useful when we work with databases, numerical
calculations, graphics and any other type of automation.
To start working with this type of file, we will have to install the necessary
library and this is done through the command "pip3 install openpyxl" in the
Python terminal.

Once our command has been executed, the openpyxl module will be
installed in our Python file.

Now we will create our first xlsx file:

In this example we can see that we have created our file by importing the
workbook function, which belongs to the openpyxl module, then we have
added our parameters such as: "wb" assigning the workbook function and
declaring that it will be our working document, then we add the name and
save the file.

Add information to the file with the xlsx module:

To add information to our file, we will rely on the append function


Now, to our document [Link], we have added a tuple that contains
words like Python, document. Once we have created this, the append
function will allow us to add the information contained in the tuple in a
message.

Here we can see that the main function of append() is to admit iterable data
such as tuples.

Read documents in xlsx:

To read an xlsx file, we will only need to import the load_workbook class
and know the name of the file we are going to work with. It is also very
important that the files are in the same folder in which the program is
stored; otherwise, an automatic error will be generated.

Once this is done, we will specify the object to work with, and we will ask
for the information we need to read in order to finally print and compile it.

Handling PDF files


Now we are going to learn to work with "Portable Document Format" files,
which have grown significantly over the years and have taken a place of
great importance in educational and work environments, this due to their
endless benefits that these have, allowing these types of files to add access
keys in order to protect a very important document and even add their own
watermark to prevent possible plagiarism in the future.

PDF files can be opened from any device (computer, tablet, smartphone),
and their weight is much lower compared to the weight of a common txt
document, as these pdf files are automatically compressed once they are
created. Therefore, the ability to edit an already created PDF file is very
complicated by its level of protection.

Other noteworthy data is that these documents can be viewed from any
device, as it is not necessary to have a specific program; also the weight of
the files is much lower because these texts are compressed unlike Word
documents, which is why in this chapter we will only learn to create such
files.

First, we will download the library with the command "Pip3 install fpdf".
With this simple example, we can observe the level of difficulty of working
with a PDF file. We observe that we need a lot of commands, we will start
with the FPDF class of the fpdf library, we will create our pdfdoc object (it
is recommended that the names have coherence to avoid confusion, but it
can be of your preference), this will be our pdf document.

Once we have created this, we are going to customize what is format, size
and font style through the set_font command.

Next, we will add a page with the command add_page(), this will be the
page on which we are going to write since the function fdpf is not able to
create a blank page by default. Here we are going to insert the information
with the help of the cell() function; this will contain the width and height
that our cell will occupy.

Finally, let's save our document with the command output() together with
the arguments that accompany it to store our file with its name. It is
important that it contains the ".fpdf" so that the program understands that
we want a pdf file, and we end up with an F string.
Handling of BIN Type Files
As we have been learning, in Python, there is a great variety of file types,
which are not exclusively text files, some are processed line by line and
others are going to be processed byte by byte, giving a different meaning to
the program. It is important that these files are manipulated in their correct
format because otherwise, this will generate an error.

The files of the Binary format are nothing more than adding a b in the
parameters of our mode.

When we are going to manage a file whose type is binary, it is very


important that we have in mind that we must know very well the current
position in which the data we need is, so that we can modify it correctly.

If we do not know the current position of the data, the [Link]() function
will indicate the number of bytes that have elapsed since we started with
our file.

If we want to modify the current position of our file, we will use the
function [Link](star,from) since this will allow us to move to a
certain number of bytes from the beginning to the end of the file.
Chapter 9: Exceptions

Exceptions can be defined as errors that occur during the execution of the
program. When the syntax of the code is written correctly, and during its
execution, something unexpected happens, an error that does not allow to
execute the line of code where the error is manifesting and the subsequent
ones.

An unexpected error in the line of codes could be considered important


depending on how big is the program we are handling; if we have a
program of hundreds or thousands of lines of codes, when the program
starts to execute, the following happens, we already know that the execution
flow goes in a top-bottom direction starting with the first line of codes and
goes down with the code or the rest of the lines of code; if the execution
flow finds in its way with a line of codes that generates an error that as we
mentioned before we have not foreseen, what is going to happen is that the
rest of the lines of code are not going to be able to execute.

In this case, the program will fail when reaching the code line where we get
to the unexpected error.

And probably, the following lines are not going to be able to be executed,
and they may have important information for our program, and therefore,
we want it to be carried out. That is why it is important to know how to
solve these exceptions that can be presented to us.
Several examples could be presented at runtime; below, we will mention the
most commonly used to explain this type of errors:

When seeing the code, there are several possibilities that an error may arise,
since you can enter values that are not integers, therefore, the int() function
could generate an error, on the other hand, there is the possibility that an
error occurs in the division, because the denominator can be equal to zero,
generating an error of division between zero.
What Is the Possible Solution to This Problem?
These problems can be solved by doing what is known as "Capture or
exception control", which basically consists of telling our code to try to
perform the instruction and in the case that it cannot perform it, that at least
the rest of the program can be executed.

The line that has generated the error of the previous example is a line of
codes that do not generate a division by zero, and this is an unexpected
error. Perhaps this line will never be executed, but applying "capture or
exception control", will allow us that the rest of the lines of code that
follows after this one can be executed successfully.
The first thing we must do is discover where the error is and how it is called
and this part is very important to determine, since, if we do not find the line
of code where the error is being generated, we will not be able to apply the
necessary instruction to solve the problem.

In the case of the example, it generates a division by zero, the description of


the error would be: ZeroDivisionError: divisionbyZero, for example.

Once identified the instruction that generates the error, this instruction must
be put inside a "Try" block that means "try", and is applied just before the
instruction that generates the error, is there where we will introduce the
word "try", followed by the instruction that generates the error and then the
word "except", followed by the name of the error. Following with the
previous serious example: "ZerodivisionError" and within this clause, we
can add what we want the program to do, for example, we can add "can not
be divided by zero", and after the error message what we want to return,
return "erroneous operation".

In conclusion we can eliminate and solve the error, with "try", and in this
way we are telling the system to try to make this division or the instruction
that is generating the error, and if it does not succeed, it will execute what is
inside the "except" that for this example is the message that says "cannot be
divided by zero", this process is something similar to what happens with the
sentences "if" and "else".

This way we control an exception, maybe we can't fix the error, but we will
be able to keep executing the rest of the lines of code that follow after this
error and execute the program.

We can also capture several exceptions, that is, we can get with errors of the
type division by zero as explained above, but also can happen other types of
errors, for example, suppose that the program asks us to enter a numerical
value and add a different value to a numerical one such as a text. Obviously
it will throw us an error, and we are going to do the same as in the previous
case and in this case we would be in the presence of an error "ValueError",
and in this case we must capture several exceptions, we begin again
locating the line that contains the error or lines of codes that originate this
error of value.

The solution is to roll these two lines of code with another "try" block,
"except", where we specify the error we want to capture, as it was done in
the previous case, with the difference that now we are capturing two lines of
codes and then we generate and execute the code.

For a code to be executed, we always have the alternative of introducing the


code inside a "finally" clause, if an exception is captured or not when
applying the "finally" clause, there is no need for there to be any "except".
Now, no matter what happens inside "try", the "finally" instruction will
always be executed, whether something good happens or not.
Chapter 10: Other Topics

Python and Serial Communication in Electronic


Devices
If you want to specialize in electronics, a topic that you must handle very
well is serial communication, as it allows you to establish a communication
between devices, through a set of logic signals, being a 1 a value of 5 volts
and a 0 a ground value or 0 volts. The way to send data is sequential, bit by
bit, they can only have two values, 0 or 1, as previously said.

There are several serial communication protocols, but in this case, we will
focus on two, which are the most used at present. The RS-232 and the
RS485. The first is used almost everywhere; moreover, all computers have
an RS232 port, which has twenty-five pins and is designed to communicate
a large amount of data at a short distance. On the other hand, we have the
RS-485, mainly designed for industrial communications, over long
distances and its technology is based on transmitting binary data, by bits,
but by means of two wires, so as to inhibit the electromagnetic effects of
large wires.

Some of the projects that you could do with serial communication and
Python are device automation, equipment instrumentation, real-time
measuring devices, image processing, among other things. Therefore, we
can assure you that this tool is extremely useful for your professional life.
The library that we will use in this case is PySerial; for its installation, we
use the console and the command:

Pip3 install pyserial

With this library, we will be able to do the serial communication, from


configuring the communication ports to receiving and sending ASCII data
through the ports.

For more information, visit the library documentation:

[Link]

Python and the Databases


Databases are widely used today, since they are everywhere, from the web
pages to the data stored by banks, so this area is very important today, even
more, is an area of study for computer engineers.

But you don't need to be an engineer to venture into this area, since you can
imagine a database as an excel sheet, which will be filled, depending on the
type of item you want to enter the database. For example, imagine that you
need a database of soccer balls, since you have the balls of the World Cups
of 2002, 2006, 2018, as well as several international tournaments, so you
need a database to know the inventory of them.
Well, to design this, we need the knowledge of a very simple programming
language, but a little new for us, as is SQL, which is responsible for
programming the databases, but, in fact, the syntax is very simple, and to
program this does not take much time, a few minutes I would say.

To make use of python databases, we recommend using the PyMySQL


library. To make use of it, use the following command in the terminal:

Pip3 install pymysql

After that, you will be able to design your own databases and work with
them, either for your work or for your personal use.

For more information about this library and how to use it, visit the
following link about your documentation:

[Link]

Python and Graphical Interfaces


This is another topic of vital importance for Python, since many times, you
will imagine that it is not only to make a program and that the results are
seen in the console, because sometimes it is necessary to make a program
with a graphical interface, in such a way that the users are able to see a
work a little more elaborated. An example of this can be to design a
calculator and it cannot be just coded to show it in the terminal, because it
is necessary to make an interface that shows the keys of the numbers,
operations, the result because it is much easier for users to use that than a
terminal. The same interfaces can have buttons, images, shapes, inputs, etc..

For this case of graphical interface design, there are many libraries, but the
simplest is Tkinter, which has a cumulus of properties that allow us to make
good and beautiful interfaces and if you are a little more advanced in the
area of programming, you could use another library such as PyQT5, the
same has some similarity to C++.

For the use of Tkinter, it is not necessary to import the library of them as in
the other two previous items, but what you should use when making code is
obviously import the module through the import sentence, as follows:
From tkinter import *

For more information, visit their official documentation page:


[Link]

Already knowing all these topics that can cover Python, you can imagine
the potential you have in your hands, we can only tell you that the limits are
in your mind, get to work and program what you want.
Conclusion

Thank you for making it through to the end of Python for Beginners: A Step
by Step Crash Course to Learn Smarter the Fundamental Elements of
Python Programming, Machine Learning, Data Science and Tools, Tips and
Tricks of This Coding Language, let’s hope it was informative and able to
provide you with all of the tools you needed to achieve your goal of
becoming a programmer.

The next step is to start programming with all the tools we provided you in
this book in order to keep improving your programming skills. As you
could have seen, programming is not a very hard activity, but it is really
important to practice since if this is not done, things can be forgotten.

If you have any doubts about anything, read it again and see the examples,
imagine one of your own and code it in order to better understand the
functioning of each statement and elements.

As you could see in the last chapter, Python can be used for a lot of things,
it is almost used on everything, so, if you are good at a certain area or
profession, now that you know how to code, you should be able to develop
programs that make your daily activities easier. If you are an economist,
you can make a program that calculates the taxes or fees of certain amounts
of money, and if you are a doctor, you can make a program that calculates
the amount of solution needed at the hospital. Those are just simple
examples of what you can do and reach with this programming language

Finally, if you found this book useful in any way, a review on Amazon is
always appreciated!

You might also like