Python Report
Python Report
The Python interpreter and the extensive standard library are freely available in the form
binary and source code for the main platforms from the Python website,
http://www.python.org/, and it can be distributed freely. The same site also contains
distributions and links of many free third-party Python modules, programs and
tools, and additional documentation.
The Python interpreter can easily be extended with new functionalities and types.
data implemented in C or C++ (or other languages accessible from C). Python too
it can be used as an extension language for customizable applications.
What is Python?
Python is a programming language created by Guido van Rossum in the early
90s whose name is inspired by the English comedy group 'Monty Python'. It is a
language similar to Perl, but with a very clean syntax that promotes readable code.
Python has, however, many of the characteristics of compiled languages, for which
that could be said to be semi-interpreted. In Python, as in Java and many others
languages, the source code is translated into an intermediate machine pseudocode called
bytecode the first time it is executed, generating .pyc or .pyo files (bytecode
optimized), which are the ones that will be executed on successive occasions.
Dynamic typing
The characteristic of dynamic typing refers to the fact that it is not necessary to declare the data type.
what a certain variable will contain, but its type will be determined at runtime
execution according to the type of value assigned, and the type of this variable can change if
a value of another type is assigned to it.
Strongly typed
It is not allowed to treat a variable as if it were of a different type than it is; it is necessary
explicitly convert that variable to the new type beforehand. For example, if
we have a variable that contains a text (variable of type string) we will not be able to
treat it as a number (add the string '9' and the number 8). In other languages, the type of
the variable would change to adapt to the expected behavior, although this is more
prone to errors.
Multiplatform
The Python interpreter is available on a multitude of platforms (UNIX, Solaris, Linux,
DOS, Windows, OS/2, Mac OS, etc.) so if we do not use specific libraries for each
Our program will be able to run on all these systems without major changes.
Object-oriented programming is a programming paradigm in which the concepts of the world
real relevant to our problem are translated into classes and objects in our program. The
The execution of the program consists of a series of interactions between the objects.
Python also allows imperative programming, functional programming and
aspect-oriented programming.
Why Python?
Python is a language that everyone should know. Its syntax is simple, clear, and straightforward;
dynamic typing, memory management, the large number of libraries available and the
the power of language, among others, makes developing an application in Python
simple, very fast and, more importantly, fun.
The syntax of Python is so simple and close to natural language that the programs
Those developed in Python seem like pseudocode. For this reason, it is also one of the
best languages to start programming.
Python is not suitable, however, for low-level programming or for applications.
in which performance is critical.
Some success stories in the use of Python are Google, Yahoo, NASA, Light Industries.
& Magic, and all Linux distributions, where Python increasingly represents a certain amount.
percent more of the available programs.
Python installation
Jython, IronPython, PyPy, etc. CPython is the most used, the fastest, and the most mature.
When people talk about Python, they are usually referring to this implementation. In this case
Both the interpreter and the modules are written in C. Jython is the implementation in Java.
of Python, while IronPython is its counterpart in C# (.NET). Its interest lies in
that by using these implementations, all available libraries can be used for
the Java and .NET programmers. PyPy, finally, as you might have guessed from the name,
it is an implementation in Python of Python.
Basic tools
There are two ways to execute Python code. We can write lines of code in the
interpret and get a response from the interpreter for each line (interactive session) or
We can write the code of a program in a text file and execute it.
When conducting an interactive session, it is advisable to install and use iPython, instead
from the interactive console of Python. It can be found inhttp://ipython.scipy.org/iPython
it has very interesting added features, such as autocomplete or the operator
(to enable the autocomplete feature in Windows, it is necessary to install
PyReadline, which can be downloaded fromhttp://ipython.scipy.org/moin/PyReadline/Intro)
The autocomplete function is activated by pressing the tab key. If we type 'fi' and press
Tab will show us a list of the objects that start with fi (file, filter, and finally). If
we write file. and press Tab it will show us a list of the methods and properties of
file object.
The operator ? shows us information about objects. It is used by adding the symbol of
question mark at the end of the name of the object that we want more information about.
Basic types
In Python, the basic types are divided into:
Numbers, such as 3 (integer), 15.57 (floating point) or 7 + 5j (complex)
Text strings, such as 'Hello World'
Valores booleanos:•True (cierto) y False (falso).
Enteros
The integers are those positive or negative numbers that do not have decimals.
(besides zero). In Python, they can be represented using the int type (short for integer).
or the long type. The only difference is that the long type allows storing larger numbers.
large. It is advisable not to use the long type unless necessary, to avoid wasting
memory.
When assigning a number to a variable, it will have type int, unless the number
It is so big that it requires the use of the long type.
type(int) would return int
entero = 23
We can also tell Python to store a number using long by adding
an L at the end:
type(int) would return long
23L
Real
Real numbers are those that have decimals. In Python, they are expressed using the type
float. In other programming languages, like C, we also have the double type, similar
a float but with greater precision (double = double precision). Python, however, implements
its low-level float type using a double type variable in C, that is, using 64
bits, then in Python it is always double precision.
real = 0.2703
Complexes
Complex numbers are those that have an imaginary part. If you were not aware of their
existence, it is more than likely that you will never need it, so you can skip it
this section calmly. In fact, most programming languages lack
of this type, although it is very used by engineers and scientists in general.
In case you need to use complex numbers, or you are simply curious,
I will tell you that this type, called complex in Python, is also stored using floating point,
because these numbers are an extension of real numbers. Specifically, they
store in a C structure, composed of two double type variables, serving one
one to store the real part and the other for the imaginary part.
Complex numbers in Python are represented in the following way:
2.1 + 7.8j
Operators
Arithmetic operators
Chains
Strings are nothing more than text enclosed in single quotes ('string') or double quotes.
("chain"). Within the quotes, special characters can be added by escaping them with
, like , the newline character, or , the tab character.
A string can be preceded by the character u or the character r, which indicate,
respectively, which is a string that uses Unicode encoding and a string
raw (from English, raw). Raw strings are distinguished from normal ones in that the characters
Escaped using the backslash (") are not replaced with their counterparts.
äóè
\n
It is also possible to enclose a string in triple quotes (either single or double). This way
this way we can write the text in several lines, and when printing the string, the will be respected
line breaks that we introduced without having to resort to the character \n, as well as the quotes without
having to escape them.
first line
this will be seen on another line
COLLECTIONS
In this part we will see some types of data collections: lists, tuples, and dictionaries.
Lists
The list is a type of ordered collection. It would be equivalent to what in other languages is
known as arrays, or vectors.
Lists can contain any type of data: numbers, strings, booleans, ... and also
lists.
Creating a list is as simple as indicating items between brackets, separated by commas.
values we want to include in the list:
l = [22, True, “una lista”, [1, 2]]
We can access each of the elements of the list by writing the name of the list and
indicating the index of the element in brackets. Keep in mind, however, that the index
the first element of the list is 0, not 1:
[11, False]
mi_var is 11
If we want to access an element of a list included within another list, we will have to
use this operator twice, first to indicate which position of the outer list
we want to access, and the second to select the element from the inner list:
l = [“una lista”, [1, 2]]
mi_var = l[1][0] # mi_var equals 1
The use of brackets to access and modify the elements of a list is common in
many languages, but Python offers us several very pleasant surprises.
One curiosity about the [] operator in Python is that we can also use numbers.
negatives. If a negative number is used as an index, this translates to the index
start counting from the end, to the left; that is, with [-1] we would access the last one
element of the list, with [-2] to the penultimate, with [-3] to the antepenultimate, and so on.
Tuples
Everything that applies to lists can also be used for tuples, with the exception of the
way to define it, for which parentheses are used instead of brackets.
(1, 2, True, 'python')
In fact, the constructor of the tuple is the comma, not the parentheses, but the interpreter shows
the parentheses, and we should use them, for clarity.
>>> t = 1, 2, 3
>>> type(t)
type 'tuple'
It is also important to note that it is necessary to add a comma for single-element tuples.
element, to differentiate it from an element in parentheses.
(1)
>>> type(t) type "int"
(1,)
>>> type(t)
type 'tuple'
To refer to elements of a tuple, like in a list, the operator [] is used:
mi_var is 1
(1, 2)
We can use the [] operator because tuples, like lists, are part of
of a type of objects called sequences.
hello world
c[0] # h
world
c[::3] # hauo
Returning to the topic of tuples, their difference from lists lies in the fact that tuples do not have
these modification mechanisms through such useful functions that we were talking about
end of the previous section.
They are also immutable, meaning their values cannot be modified once created; and they have
a fixed size.
Dictionaries
Dictionaries, also called associative arrays, are named as such because they are
collections that relate a key and a value. For example, let's look at a dictionary of
movies and directors:
Richard Curtis
"Kill Bill": "Tarantino"
Amélie
The first value is the key and the second is the value associated with the key. As a key
we can use any immutable value: we could use numbers, strings, booleans,
tuples, ... but not lists dictionaries, since they are mutable. This is because the dictionaries
scenarios are implemented as hash tables, and when introducing a new key-value pair
In the dictionary, the hash of the key is calculated in order to later find the entry.
corresponding quickly. If the key object were modified after being
introduced in the dictionary
The main difference between dictionaries and lists or tuples is that values
stored in a dictionary are accessed not by their index, because in fact they do not have one.
order, but by its key, using the operator [] again.
Richard Curtis
Just like in lists and tuples, this operator can also be used to reassign values.
Quentin Tarantino
However, in this case, slicing cannot be used, among other things, because the
Dictionaries are not sequences, but mappings (mapped associations).
FLOW CONTROL
In this section, we will look at conditionals and loops.
Conditional sentences
If
The simplest form of a conditional statement is an if followed by the
condition to evaluate, colon (:) and on the next line indented, the code to execute in
in case that condition is met.
mundogeek.net
if fav is equal to "mundogeek.net"
if fav == "mundogeek.net":
You have good taste!
Thank you
It is important to ensure that the code is indented exactly as it has been done in the example, that is,
make sure to press Tab before the two print statements, as this is the way to
In Python, to know that your intention is for both prints to execute only in the case
that the condition is met, and not that the first string is printed if it is met
condition and the other always, something that would be expressed like this:
if fav == "mundogeek.net":
You have good taste!
Thank you
In other programming languages, code blocks are defined by enclosing them between
keys, and indenting them is simply a good practice to make it easier
follow the flow of the program at a single glance.
if ... else
What would we do if we wanted certain orders to be executed in the event that the
condition was not met? Surely we could add another if that had as a condition the
negation of the first
if fav == "mundogeek.net":
You have good taste!
Thank you
if fav != "mundogeek.net":
Wow, what a shame
but the conditional has a second construction that is much more useful:
if fav == "mundogeek.net":
You have good taste!
Thank you
else:
Wow, what a shame
We see that the second condition can be replaced with an else.
if ... elif ... elif ... else
if number < 0:
Negative
elif number > 0:
Positive
else:
Zero
elif is a contraction of else if, therefore elif number > 0 can be read as 'if not, if
the number is greater than 0". That is, first the condition of the if is evaluated. If it is true, then
executes its code and continues executing the code following the conditional; if it is not met,
the elif condition is evaluated. If the elif condition is met, its code is executed and it
continues executing the code after the conditional; if it is not met and there is more than one elif
it continues with the next in order of appearance. If the condition of the if is not met neither
none of the elifs, the code of the else is executed.
A if C else B
There is also a construction similar to the ? operator from other languages, which is nothing more than
a compact way to express an if else. In this construction, the predicate C is evaluated and
A is returned if it is met or B if it is not met: A if C else B. Let's see an example:
even
Loops
While conditionals allow us to execute different code segments
depending on certain conditions, loops allow us to execute the same fragment
of code a certain number of times, as long as a specific condition is met.
While
The while loop executes a code fragment as long as a condition is met.
edad = 0
while age < 18:
age = age + 1
Congratulations, you have
The variable age starts at 0. Since the condition that age is less than 18 is
true (0 is less than 18), entering the loop. Age is increased by 1 and the message is printed
informing that the user has completed a year. Remember that the operator + for the
chains work by concatenating both chains. It is necessary to use the str function (destring,
(string) to create a string from the number, since we cannot concatenate numbers
and chains.
Another keyword that we can find within loops is continue.
As you may have guessed, it just goes directly to the next iteration of the
loop.
edad = 0
while age < 18:
age = age + 1
if age % 2 == 0:
continue
Congratulations, you have
for ... in
In Python, 'for' is used as a generic way to iterate over a sequence. And as such
try to facilitate its use for this purpose.
OBJECT-ORIENTED
Classes and objects
To understand this paradigm, we first need to understand what a class is and what a
object. An object is an entity that groups related state and functionality.
the object's state is defined through variables called attributes, while the
functionality is modeled through functions known as
methods of the object.
In Python, classes are defined using the keyword class followed by the name of the
class, colon (:) and then, indented, the body of the class. As in the case of
the functions, if the first line of the body is a string, this will be the string
of the class documentation or docstring.
The first thing that catches the attention in the previous example is the curious name it has.
the __init__ method. This name is a convention and not a whim. The __init__ method,
with a double underscore at the beginning and end of the name, it runs just after creating a
new object from the class, a process known as instantiation. The
The __init__ method serves, as its name suggests, to perform any process of
initialization that is necessary. As we see, the first parameter of __init__ and the rest of
The methods of the class are always self.
Inheritance
There are three concepts that are fundamental to any object-oriented programming language.
objects: encapsulation, inheritance, and polymorphism.
In an object-oriented language, when we make a class (subclass) inherit from another
class (superclass) we are making the subclass contain all the attributes and methods
that had the superclass. However, the act of inheriting from a class is also referred to as
to extend a class.
To indicate that a class inherits from another, the name of the class from which it inherits is placed.
in parentheses after the class name:
Multiple inheritance
In Python, unlike other languages like Java or C#, multiple inheritance is allowed.
that is, a class can inherit from multiple classes at once. For example, we could have a
Crocodile class that will inherit from the Terrestrial class, with methods like walk() and attributes
like walking_speed and of the Aquatic class, with methods like swim() and attributes like
swimming_speed. Just list the classes from which it inherits, separated by commas:
Polymorphism
The word polymorphism, from the Greek poly morphos (many forms), refers to the ability
of objects of different classes responding to the same message. This can be achieved by
through inheritance: an object of a derived class is at the same time an object of the
parent class, so that wherever a parent class object is required, it can also be
use one from the child class.
Python, being dynamically typed, does not impose restrictions on the types that can be passed to it.
to a function, for example, beyond the fact that the object behaves as expected: if it is going to
call a method f() of the object passed as a parameter, for example, obviously the
the object will have to have that method. For that reason, unlike strongly typed languages
static like Java or C++, polymorphism in Python is not very important.
Encapsulation
Encapsulation refers to preventing access to certain methods and attributes of the
objects establishing what can be used from outside the class.
This is achieved in other programming languages like Java using modifiers of
access that defines whether anyone can access that function or variable (public) or if it is
access to the class itself is restricted (private).
In Python, there are no access modifiers, and what is usually done is that access to
a variable or function is defined by its name: if the name starts with two
underscores (and does not end with two underscores) refers to a variable or function
private, otherwise it is public.
Higher-order functions
The concept of higher-order functions refers to the use of functions as if they were a value.
anyone will be dealt with, allowing functions to be passed as parameters to other functions or
return functions as a return value.
Higher-order iterations over lists
map(function, sequence[, sequence, ...])
filter(function, sequence)
reduce(function, sequence[, initial])
Decorators
A decorator is nothing more than a function that takes a function as a parameter and
returns another function as a result. For example, we could want to add the functionality
that the name of the called function would be printed for debugging purposes
Packages
If modules are used to organize code, packages are used to organize the
modules. Packages are special types of modules (both are of type module) that
they allow grouping related modules. While the modules correspond at a physical level
With the files, the packages are represented by directories.
To make Python treat a directory as a package, it is necessary to create a file
__init__.py in that folder. In this file, elements that belong to can be defined.
this package, as a constant DRIVER for the bbdd package, although usually it
it will deal with an empty file. To make a certain module be within a
package, it is enough to copy the file that defines the module to the package directory.
Like modules, to import packages, import and from-import are also used and the
character . to separate packages, subpackages, and modules.
Standard output
The simplest way to display something to standard output is by using the statement
print, as we have seen countless times in previous examples. In its most basic form to
the keyword print is followed by a string, which will be displayed on the standard output when executed
the estate.
The simplest specifiers are formed by the symbol % followed by a letter that
indicate the type with which to format the value For example:
Files
Files in Python are file type objects created using the open function.
function takes as parameters a string with the path to the file to open, which can be relative
or absolute; an optional string indicating the access mode (if not specified, it accesses
in read mode) and, finally, an optional integer to specify a buffer size
different from the one used by default.
The access mode can be any logical combination of the following modes:
• : read, reading. Opens the file in read mode. The file must exist.
previously, otherwise an IOError exception will be raised.
'w': write. Open the file in write mode. If the file does not exist, it
create. If it exists, overwrite the content.
'a': append, add. Opens the file in write mode. It differs from the 'w' mode in
that in this case the content of the file is not overwritten, but rather it starts
to write at the end of the file.
‘b’• : binary, binary.
+: allows simultaneous reading and writing.
‘U’: universal newline, universal line breaks. Allows working with files that
they have a format for line breaks that does not match that of the platform
actual (in Windows the CR LF character is used, in Unix LF and in Mac OS CR).
File reading
For reading files, the methods read, readline, and readlines are used.
File writing
For file writing, the write and writelines methods are used. While the
First, it works by writing a string of text to the file that it takes as
parameter, the second takes as a parameter a list of strings indicating
the lines we want to write in the file.
CONCLUSIONS
1. A language very similar to Pseudocode, quite clean with a readable syntax due to its
great similarity to natural language.