Programación Python para Principiantes - Parte4
Programación Python para Principiantes - Parte4
• 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.
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.
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”.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
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
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.
We can define Python files as a set of bytes that will contain a certain
composite structure.
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.
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.
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.
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.
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([ ]) Method
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.
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
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.
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.
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.
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.
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.
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.
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.
Here we can see that the main function of append() is to admit iterable data
such as tuples.
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.
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.
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.
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.
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.
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:
[Link]
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.
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]
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 *
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!