Learning Python ENG Sample 1-4
Learning Python ENG Sample 1-4
Introduction to computer
programming
se
a very high and varied number of tasks. This depends on the
fact that these devices can be instructed, for each of the tasks
lu
they are required to perform, through programs. A program is
na
a set of instructions that a computer must follow systemati-
tio
cally to perform a certain task, whether it is a simple or very
a
ingly, but the logic remains the same. Apps for smartphones
ed
and tablets are no exception: they are nothing more than pro-
grams developed with a programming language, optimized for
or
mobile devices.
-f
se
language with a reasonable effort. Although the syntax of the
lu
various languages is different and requires a specific study, the
na
main logic and constructs are widely shared. Learning the fun-
damentals of programming with Python therefore enables ac-
tio
the current scenario and very appealing in the job market. For
e
se
tions);
memory: necessary to store both data and instructions. Com-
lu
XX
puters have different types of memories: ROM, RAM, mass
na
storage (hard disks, flash memories etc.);
tio
XX input/output devices: this category includes keyboards, dis-
a
Input
&
Output CPU Memory
devices
BUS
3
Another thing that has remained unchanged is the lan-
guage used by the computer CPU. A fundamental concept is
that the CPU of any computer «speaks» and understands a sin-
gle language, called machine language. This language consists of
0 and 1 alone: any type of information is computed, managed
and stored by the CPU and computer memory in the only form
of binary digits 0 and 1 (each of which represents a bit of in-
formation). Therefore all programming languages, even those
more evolved (to be relatively easy, understandable and usable
by developers and users), always include a sort of «translation
system» into machine language, without the need for user in-
tervention.
In the 1950s, when computers were as big as a whole room
se
and coding was in the early stages, developers wrote the pro-
lu
gram instructions as a sequence of 0 and 1, and used punched
na
cards to physically memorize the instructions. Only simple
tio
instructions could be entered, such as reading from memory
a
fined tasks.
-f
se
bet, different punctuation marks and other characters; each of
lu
these characters corresponds to a number, and storage in bytes
na
takes place using this number converted into binary code. For
tio
example, the capital letter A corresponds to the code 65 in the
ASCII table, B to 66, C to 67 and so on. The ASCII coding sys-
a
uc
tem was developed in the 1960s, and has been widely used by
ed
se
the «brain» of the computer, is not equipped with any intelli-
gence: everything it does depends on the instructions commu-
lu
nicated to it by the programs. A program is nothing but an or-
na
dered set of instructions that tells the CPU what to do. These
tio
instructions must be very detailed, because in itself the CPU is
a
se
errors have occurred: it will therefore be necessary to return to
lu
the code, correct it and then compile it again. An example of a
language to be compiled is C. na
The interpreted software, on the other hand, is translated
tio
se
creasingly used in correspondence with the diffusion of com-
lu
puters capable of storing programs (different from the previ-
na
ous computers programmed exclusively through switches and
tio
cables). Assembly for the first time introduced, in place of the
simple numerical sequences of 0 and 1, some mnemonic words,
a
uc
such as add (to add two numbers), mul (to multiply), mov (to
ed
se
the goal step by step.
lu
Python is considered a multi-paradigm language (or «mixed
na
paradigm»), and was created with the aim of taking the best of
existing paradigms and languages, combining their qualities,
tio
tal features and basic structures of Python will have been clar-
pl
Requisites Analisys
Design
Implementation
Debugging
Test Execution
se
lu
na
It is possible to meet different representations of the program
tio
development cycle (or development process, or life cycle), but
a
variations.
ed
se
XX the statements must be expressed unambiguously.
lu
The ability to split a task into its components is one of a pro-
na
grammer’s main operations. In practice, once an algorithm that
tio
leads to the solution of a problem has been developed, howev-
a
into statements.
Algorithms are commonly represented by flow charts, i.e.
or
Start
Read Length
Read Width
se
lu
Calculate Area
Length x Width na
a tio
uc
Show Area
ed
or
-f
End
e
pl
se
have thought of later: a descendant of the ABC [another lan-
lu
guage previously devised by Van Rossum], which should have
belonged to the Unix hackers. I chose Python as the name of
na
the project, being slightly irreverent (and I’m a big fan of Mon-
tio
ty Python’s Flying Circus)». The name Python therefore derives
a
for Python:
XX a simple language, intuitive and powerful as its major ad-
versaries;
XX free and open source, so that anyone could participate in its
development;
XX an easily understandable code, such as spoken English;
XX great for everyday tasks, as it allows for short development
times.
One reason for the popularity of Python certainly lies in the
simplicity of the code, which facilitates understanding for be-
ginners. Python code is easy to read and easy to learn, while
still being a very powerful language.
13
Over the years Python has grown, evolved (under the direct
control of Van Rossum) and has won increasing popularity, first
with the Internet arena and, especially in recent years, with the
field of data science. Van Rossum worked from 2005 to 2012
in Google, and since then in Dropbox, not surprisingly two gi-
ants that make extensive use of Python in their web services.
Python is an open source language with a huge following
of volunteers who are constantly trying to improve it. This
allows the language to stay up to date with the latest trends.
The community is very large, and programmers can reuse ex-
isting code and features instead of developing them over and
over again.
Python is today one of the most popular languages (see the
se
TIOBE index mentioned in § 1.4) and measures against real «sa-
lu
cred monsters» like Java, C and C++. These are consolidated lan-
na
guages that have received great attention by the academic and
tio
business world, but which, being more complicated, are main-
a
language are becoming much sought after. There are also ad-
-f
ditional libraries that make Python very versatile (we will talk
e
XX data analysis;
XX machine learning;
XX web development;
LEARNING PYTHON
ers, Iron Man, Star Trek, Pirates of the Caribbean and many others.
In the Web, it is employed by giants like Google, Mozilla Cor-
poration, Dropbox, and YouTube. It is used by NASA and it is 1
at the center of the ESA project that will bring a space probe to
se
lu
na
a tio
uc
ed
or
-f
e
pl
m
Sa
15
2
Introduction to Python
se
described as a high-level, interpreted, interactive, object-ori-
ented, simple programming language that uses dynamic typ-
lu
ing, strongly typed, incorporating high-level modules and data
na
types, and portable.
tio
We have already introduced the concepts of high-level lan-
a
grams.
m
Sa
Introduction to Python
less «formal» than other languages, is the dynamic typing of vari-
ables. To understand this concept fully, it is necessary to have
become familiar with the concept of variable and with the types
of data. We will discover (Chapter 4) that variables are funda-
mental elements of a program because they contain the values
necessary or resulting from the calculations and operations that
the program performs. In many other languages, when intro-
ducing a variable it is necessary to use a more or less complex
syntax, which declares from the start which type of data can
be stored in that variable (in this case we talk about static typ-
se
ing). In Python, instead, it is sufficient to assign an initial val-
lu
ue to a variable to define its type, without further formalisms.
na
The data type of the variable can also change if another value
tio
is assigned with a different type. At the same time, however,
data typing is very important in Python and it is not possible to
a
uc
se
Now, the question is: where do we start? The first thing to
lu
do to code in Python is to download and install the software,
na
in the latest version available. As we will see, a basic develop-
ment tool is included in the Python installation and, due to its
tio
but the concepts related to the code do not vary in any case
pl
if you use another tool. Only the interface and the possibili-
m
To download Python we
2.2 How to install Python should connect to the of-
ficial website www.python.
org. You can also download from other websites, but here you
will always find the most up-to-date version of the software
as soon as it is released, along with the official documentation
18
FigurE 2.1 T
he home page of the website www.python.org
with the link to download Python 2
Introduction to Python
se
lu
na
a tio
uc
ed
tion, the menus and dialog boxes of the tools that are installed.
-f
ing on this link gives access to a page that contains all the in-
formation on the latest version and the variations of the instal-
lation file based on the operating system in use.
There is also a Downloads section, higher up (just below the
word pythonTM), which opens a panel with the download link
for the latest version. This immediately downloads the basic
version for the operating system in use, without proposing any
choice (suitable for beginners).
Upon clicking on the link, the installation file will be down-
loaded to your computer (it may be called python-3.x.x.exe or
similar, depending on the operating system). Starting the ex-
ecutable file, the installation procedure will start. Python will
show a dialog box like the one in Figure 2.2.
19
FigurE 2.2 The dialog to install Python
se
lu
na
a tio
uc
latest version.
pl
Once the Add to PATH item has been selected, you can click
m
Install Now. This will actually start the installation, which will
Sa
take a few minutes. When finished, you can close the dialog and
open Python from your computer’s menu. Along with the in-
terpreter and the development environment, the Python doc-
umentation and manuals will also be installed.
Introduction to Python
XX the editor, which is used in script mode, i.e. allows you to cre-
ate the actual programs, which can be saved in the comput-
er’s memory and be executed whenever you wish.
IDLE is part of the programs called, in general, IDE (Inte-
grated Development Environment), that is programs that pro-
vide all the necessary tools to write, execute and test a pro-
gram. IDLE integrates some features specifically designed to
help write Python code. For example, the code is automati-
cally colored as it is written, so that keywords, functions and
se
other program elements are displayed in specific colors that
allow you to distinguish them at a glance (and also to imme-
lu
diately understand if the words are have been correctly writ-
na
ten, since otherwise they do not color). This makes it easier
tio
to write and read programs.
a
21
and execute them. For this reason, we often refer to the Python
shell as the «interpreter». The shell shows an opening message
that contains the indication of the installed version.
The symbols >>> represent the prompt, which indicates
that the interpreter waits for the insertion of a statement.
When you type a statement, directly after the prompt, this is
executed and the interpreter waits for a new statement (show-
ing the prompt again). For example, the following statement
displays the text contained in quotes:
>>> print('Python forever')
When you press the Enter key on the keyboard, the interpret-
se
er will execute the statement and re-propose the prompt, wait-
ing for a new statement.
lu
>>> print('Python forever')
na
tio
Python forever
>>>
a
uc
message. This is very useful when you are learning to code, because
or
>>>
If we write, instead, print('hello!') we will get in re-
sponse hello!. In this case, we wrote something that makes 2
sense to Python, and we got a consistent response:
Introduction to Python
>>> print('hello!')
hello!
>>>
se
>>>
lu
In the shell, we can do all possible experiments. However, there
na
is no way to «clean up» the shell window, so if you want to start
tio
from a clean situation, the only way is to close it and reopen it
a
on the keyboard.
ed
The editor allows you to save the statements in a file with a .py ex-
e
will cause the interpreter to start in script mode (Figure 2.4): the
m
Sa
code will be read and run statement by statement, until the end
of the program. Several IDLE settings can be customized. The
command to access the settings is Options → Configure IDLE.
The Settings dialog box appears (Figure 2.5).
In the Fonts/Tabs tab, it is possible to configure, for exam-
ple, the font type and the font size used in the shell and in the
editor, or the width of the indentation (which is inserted in the
code by pressing the Tab key).
In the Keys tab, instead, it is possible to show (and eventu-
ally modify, if necessary) the key combinations (shortcuts) us-
able when programming in IDLE. It may be useful to take note
of some combinations, one out of all history-previous, which
23
se
lu
na
tio
Introduction to Python
In the Highlights tab, it is possible to display the colors as-
signed in IDLE to each element of the language:
XX built-in functions (i.e. Python’s default functions, such
as print) are in purple;
XX strings are in green;
XX output is in blue;
XX errors are in red.
Moreover, among the elements that we will meet later, espe-
cially using the editor:
se
lu
XX Python keywords are in orange;
XX na
defined names, such as user-defined function names and
classes, are in blue;
tio
se
lu
na
tio
Once the code has been written, you can save the program on
a
command File → Save As. When the file name contains several
ed
it has been saved for the first time, is the usual Save. In IDLE
-f
but creates a second copy of the file leaving the original open.
pl
m
before continuing.
When a program is run, the output is displayed in the shell.
If, at the time of execution, Python detects a syntax error, a di-
alog box will appear with the invalid syntax message. By
clicking OK in the dialog box, the editor will highlight the er-
ror location in the code. To check the syntax of a program be-
fore running it, in order to highlight any errors, you can choose
the Run → Check Module command.
If the saved program has been closed and you need to re-
26
Introduction to Python
To open an existing program, the command (from the shell or
from the editor, indifferently) is File → Open.
It may happen, when writing a program, to write long
statements that become unreadable in the editor window. In
this case, it is possible to wrap within the code, for improved
readability. This will not produce any effect in the program
output. To do this, simply enter the character \ (backslash)
in the code, where you want to wrap the text. The follow-
ing code, for example, is a single statement that will give
the result of the whole piece of text reported in the differ-
se
ent lines (the backslashes allow to break the code in more
lu
lines for greater legibility, where necessary, without affect-
ing the output): na
tio
print("I sing the body electric, \
a
se
although not fully intelligible (having not yet learned the if-
lu
elif-else constructs and the variables) will still be readable
na
for an inexperienced eye, and this is due to the ease in recog-
tio
nizing each statement block, thanks to indentation:
a
uc
access = False
or
else:
m
access = True
Sa
Introduction to Python
as def for lambda return
assert del from None True
async elif global nonlocal try
await else if not while
break except import or with
class False in pass yield
se
(for this reason it is called reserved). Table 2.1 shows all the
Python keywords: in the next chapters, we will discover the
lu
meaning of most of these keywords and use them in Python
na
statements.
tio
In addition to keywords, in programming languages there
a
>>> 37*6
m
222
Sa
>>> 24/4
6.0
to enclose strings with quotes (' ') or quotation marks (" ").
>>> print('John Snow')
John Snow
>>> print("John Snow")
John Snow
In the case, less common but still possible, in which the string
contains in turn quotation marks, it is necessary to enclose it
in quotes:
se
>>> print('You have to read "Macbeth" and
lu
write a summary by tomorrow!')
na
You have to read "Macbeth" and write a
tio
summary by tomorrow!
a
uc
cuss it in § 2.6).
m
However, there are two operators that work with strings, al-
though their meaning changes:
XX the + operator, used on strings, performs a concatenation;
30
Introduction to Python
superman
>>> print('Python' * 4)
PythonPythonPythonPython
se
The syntax error occurs when we do not respect one of Py-
lu
thon syntax rules, and shows the error message SyntaxEr-
ror: invalid syntax. For example, if writing a print func-
na
tion we inadvertently add a second closed or open parenthe-
tio
sis, it is enough for Python to return a syntax error message:
a
uc
may cause an error when trying to run it. Errors detected dur-
ing execution are called exceptions and are not always fatal: in
e
pl
The last line of the error message indicates what happened. Ex-
ceptions are of different types, and the type is shown as part
of the message (for example ZeroDivisionError, NameEr-
ror or TypeError) along with a brief explanation (in the ex-
ample: division by zero).
31
Comments When the program grows in size and
2.6 and docstring becomes more complex it is a good
habit to add comments, which serve
to document the various steps of the program.
Comments are short notes, which can be inserted at differ-
ent points in a program and explain how the statements work
or what objectives they have. Comments can be entered in two
ways:
XX when they follow a line of code, only by preceding them with
the symbol #;
XX when they are between several lines of code or at the begin-
ning of the program, in addition to the # symbol, insert-
se
ing them between triple quotation marks (""" """) or triple
lu
quotes (''' '''). In this case, the comments can also go over
several lines. In the case of a comment made in this way, po-
na
sitioned at the beginning of the program or at the beginning
tio
of a custom function we speaks (as we will see in Chapter 7)
a
of a documentation string.
uc
ed
Go!
The code \t, instead, aligns the text to the tabulation:
>>> print('String \t with tabulator')
2
Introduction to Python
String with tabulator
se
Escape Description Example Result
lu
code
Double quote
ed
Hello
-f
Hello
print("Hello\tWorld!")
m
\t Tabulation World!
print("Bye\tbye!")
Sa
Bye bye!
se
Print('hello!')
lu
NameError: name 'Print' is not defined
na
The flexible management of Python spaces allows instead writing
tio
the first bracket attached or detached from the print function.
a
are not visible, call tips can be activated with the Edit → Show
-f
>>>
FigurE 2.7 T
he print function with the call tip that
describes its syntax 2
se
es a different output (not three different texts but a single
lu
text string):
na
>>> print('I, am, me')
tio
I, am, me
a
>>>
uc
ed
the hyphen:
Sa
function.
TABLE 2.3 Python’s built-in functions
abs() issubclass()
all() iter()
any() len()
ascii() list()
bin() locals()
bool() map()
breakpoint() max()
bytearray() memoryview()
bytes() min()
callable() next()
se
chr() object()
lu
classmethod() oct()
compile() open()
complex()
na
ord()
tio
delattr() pow()
a
dict() print()
uc
dir() property()
ed
divmod() range()
or
enumerate() repr()
-f
eval() reversed()
exec() round()
e
pl
filter() set()
m
float() setattr()
Sa
format() slice()
frozenset() sorted()
getattr() staticmethod()
LEARNING PYTHON
globals() str()
hasattr() sum()
hash() super()
help() tuple()
hex() type()
id() vars()
input() zip()
int() __import__()
36
isinstance()
2.9
Help and other
kinds of support
Python provides some support
tools for experienced and non-ex- 2
pert programmers. Among these
Introduction to Python
is the help function, which is used in interactive mode (in the
shell) and shows information about a function, a data type or a
module. It can be used whenever we have a doubt about one of
these elements and we want to learn more. We can try to use
it on the print function: we will get information on its syn-
tax and its parameters:
>>> help(print)
Help on built-in function print in module
builtins:
se
print(...)
lu
print(value, ..., sep=' ', end='\n',
file=sys.stdout, flush=False) na
tio
Prints the values to a stream, or to sys.
a
stdout by default.
uc
default a space.
e
stream.
class _Helper(builtins.object)
| Define the builtin 'help'.
37
|
| This is a wrapper around pydoc.help that
provides a helpful message
| when 'help' is typed at the Python
interactive prompt.
|
| Calling help() at the Python prompt
starts an interactive help session.
| Calling help(thing) prints help for the
python object 'thing'.
se
>>> help()
lu
Welcome to Python 3.7's help utility!
na
If this is your first time using Python, you
should definitely check out
tio
the tutorial on the Internet at https://docs.
a
python.org/3.7/tutorial/.
uc
ed
help>
se
lu
na
a tio
uc
In addition to this, on the Web you can find all kinds of in-
formation, including parts of code ready for use. For informa-
e
pl
site www.python.org.
Sa
39
3
Calculations and data output
se
tors that allow to perform calculations in Python.
lu
In calculations, numbers (called operands) and mathematical
na
operators are involved. Python provides a series of mathemati-
tio
cal operators that allow to perform the most common arithme-
a
in the shell:
>>> 8-4
4 3
>>> 7*6
As you can see, the result of 30/6 is 5.0 and not 5, as the di-
vision operator always returns a decimal number of the float-
ing-point type (data types will be deepened in the Chapter 4).
If we want to get from two integers an integer result (without
decimals, but also without remainder) we have to use the inte-
ger division operator //.
se
>>> 30//6
lu
5
>>> 30//7 na
tio
4
a
>>> 40/6
6.666666666666667
-f
>>> 40//6
e
6
pl
m
se
and parentheses that performs a calculation and returns a
lu
value. An expression can contain both numbers and vari-
na
ables that represent numbers (a concept that we will explore
in Chapter 4). Therefore, all the following can be considered
tio
expressions:
a
uc
12 + 2
ed
(7+3)**2*20.5
or
worked_hours * pay_rate
-f
se
>>> 3 * 2 ** 2
lu
12
na
first, 2**2 is computed and then the result (4) is multi-
tio
plied by 3;
a
>>> 1 + 2 * 3
ed
7
or
first, 2*3 is computed and then the result (6) is added to 1.
-f
right to left:
Sa
se
c
lu
To convert it into a Python statement it is necessary to make
na
the * operator explicit and add the brackets to enclose the nu-
tio
merator:
a
uc
x = (2*a+b)/c
ed
+ (val9 + val10) / 2
Sa
142.85714285714286
We can round the output to the second decimal, using the for-
mat function: 3
se
The fact that the result of the format function appears in
lu
quotes indicates that it is a string. If we try to insert a for-
na
mat function inside a print, the result will be displayed with-
tio
out quotes, but it is only a difference in display (the print func-
a
142.86
-f
se
>>> print(format(123456, ',d'))
lu
123,456
na
tio
In Python there are
3.5 Functions for calculations
a
tions dedicated to
ed
15
Sa
32
The result is equivalent to the use of the exponent opera-
tor already seen: 3
se
>>> round(3.376, 1)
lu
3.4
>>> round(3.376, 2) na
3.38
tio
>>> round(3.376, 3)
a
3.376
uc
30
m
10
>>> max([12, 58, 87, 43, 21])
87
22.5
In addition to built-in functions, we will discover that there are
other types of functions: those that are part of the standard Py-
thon library (they are installed with Python, but must be im-
ported in order to be used), those that are part of third-par-
ty libraries (which must be installed and then imported before
they can be used) and the custom functions created by the user.
We will deepen the theme of custom functions in Chapter 7,
while libraries will be the subject of Chapter 11. However, we
can mention the functions of the standard library, since some
of them are widely used and may be useful in future examples.
The standard library is a set of additional modules that are
installed together with Python to perform specific tasks, but are
not immediately active. This means that when Python is load-
se
ed into memory (when the program starts) only the most com-
lu
mon functions are loaded, so as not to overload the computer’s
na
memory with functions that are not needed. When a particular
tio
function is needed, which is part of a module of the standard
library, it is necessary to import that module into the current
a
uc
Once imported, you can use its functions in the current shell
Sa
The math module also includes the sin, cos, and tan func-
tions that calculate the sine, cosine and tangent values, re-
spectively.
Another commonly used module, in the context of calcu-
lations, is random, which allows generating random numbers.
The random() function of the random module generates a ran-
dom floating-point number between 0 and 1.
se
>>> import random
lu
>>> random.random()
0.5078906679277326 na
tio
The randint(a,b) function generates an integer random
a
>>> random.randint(0,5)
4
or
-f
ules, see Chapter 11 where we will also learn about some third-
pl
NAME
math
DESCRIPTION
This module is always available. It
provides access to the
mathematical functions defined by the C
standard.
FUNCTIONS
acos(x, /)
Return the arc cosine (measured in
radians) of x.
acosh(x, /)
Return the inverse hyperbolic cosine
of x.
…
se
If we want to have only a list of the functions contained in a
lu
module, we could use the function dir (useful, as help, most-
na
ly in the shell) instead. This function will also be taken up and
tio
examined in Chapter 11.
a
uc
>>> dir(math)
['__doc__', '__loader__', '__name__', '__
or
se
grams use variables. A variable is a noun that represents a val-
ue in the computer’s memory (in such cases, it is said that the
lu
variable references such value): it is like a container, with the
na
value’s name labelled on it, in which a value is stored. To create
tio
a variable and make it reference specific values, an assignment
a
>>> width = 10
pl
m
sent the value they reference, and such value may change dur-
ing the execution of the program depending on various factors,
as we will see later.
Variables are extremely useful when used as arguments
of functions. In the example below, the value of the vari-
able width is passed to the print function.
>>> print(width)
10
se
them a value:
lu
>>> teacher_surname = 'Smith' na
>>> num_presents = 86
tio
>>> temperature = 22.5
a
uc
>>> print(teacher_surname)
Smith
>>> print('teacher_surname')
LEARNING PYTHON
teacher_surname
se
SyntaxError: can't assign to literal
lu
na
As we will examine shortly, it is not possible to use 22.5 as the
name of a variable and therefore an error occurs.
tio
It is possible to insert into the arguments of functions vari-
a
ample below:
or
surname)
e
se
example @, &, $, €, § etc.);
lu
XX must not be among Python keywords.
na
It is preferable that they do not contain accented characters.
tio
Keeping in mind that in assignment statements the name
a
tax errors:
ed
letter or an underscore.
m
Sa
se
5
lu
>>> print = 6
na
This latter instruction creates a variable called print, assign-
tio
ing it a value of 6. From now on, every time the program is run
a
longer refer to the function we have used so far, but to the val-
ed
>>> print
pl
6
m
>>> print(5)
Sa
se
4.3 Reassignment they may reference different values
lu
during the execution of a program.
na
When a variable is assigned a value, it references such value un-
til another value is assigned:
a tio
>>> price
ed
100
>>> price = 90
or
>>> price
-f
90
e
pl
1
>>> a = a + 1
>>> a 4
2
se
NameError: name 'b' is not defined
lu
Python admits assigning variables multiple values (also called
na
unpacking), which allows to initialize or reassign more than one
tio
variable with a single code line. In the following example, three
variables called alpha, beta and gamma, are initialized to the
a
uc
>>> alpha
17
-f
>>> beta
e
22
pl
>>> gamma
m
34
Sa
XX a number (1,234).
Usually we do not think about the fact that a name consists of
characters, the date and the amount of money consist of num-
bers, and so on. When we use data in a programming language,
we must consider the data type we are using in order to know
what we can do: data management implies rules that depend on
the specific language we are using, even though some of these
rules and logic are common to most high-level languages. For
this reason, it is important to understand data types and the re-
lated rules and usage: what we are going to learn in Python will
allow us to perform all the fundamental operations with data
and will constitute the starting point for programming. Most
of the definitions and logic we are going to learn can be applied
to all programming languages, for instance VBA, Java, R, Sta-
se
ta and Matlab, but also will be useful for the management of
lu
database and other IT tools related to data (including big data
management tools). na
tio
In § 1.2, we saw the way computers memorize data, and talk-
a
nary code. Starting from the conversion process, each data type
ed
used according to specific rules. The data type used in the pro-
e
the data type category they belong to, while in others (such as
Python) this happens automatically (in this case we talk about
dynamic typing).
The concept of variables, introduced at the beginning of this
chapter, is closely connected with data typing, which will now
be taken into account. In programming languages, data typing
can be either static or dynamic. In the first case, the program-
mer must declare the variable type before using it, while in dy-
58
namic typing the interpreter (or compiler) is the one who de-
cides the variable type, according to the value assigned to it.
Python uses dynamic typing, therefore specifying the type of 4
the variables is not necessary: variables assume it automatical-
se
The first value assigned to x is obviously a whole number (or
lu
integer), the second is a string, and the third is a complex data
na
type (called list), which we will analyze in Chapter 8.
tio
Python’s elementary data types are listed in Table 4.1.
When we insert an integer in Python, this is classified
a
uc
Whole number,
Integer int 112, 0, -158
positive or negative
Floating-point
Real
float number, positive 2.14, -159.1234
number or negative
Logical value:
Boolean bool True, False
true or false
String
of alphanumeric
characters, 'SEDIN', 'Python',
String str representing 'Python3', 'Web
a text. It may contain 2.0'
letters, numbers
and symbols
59
To identify the data type each value belongs to, we can use
the type function:
>>> type(10)
<class 'int'>
>>> type(7.3)
<class 'float'>
>>> type('Python')
<class 'str'>
se
>>> value = 10
lu
>>> type(value)
<class 'int'> na
>>> value = 'very high'
tio
>>> type(value)
a
<class 'str'>
uc
>>> type('Python3')
m
<class 'str'>
Sa
>>> type('10')
<class 'str'>
Or:
>>> print('Total amount: $' + format(total_
amount, ',.2f'))
Total amount: $5,227.04
se
(argument separator in the print function) and the opera-
lu
tor + (which allows string concatenation) is in the manage-
na
ment of spaces. The different arguments of the print function
tio
are returned divided by one space automatically, while string
a
amount, ',.2f'))
m
se
Depends on the applied discount percentage
lu
The instruction in the first line creates a variable called price,
na
and assign it value 100, an integer. The instruction of line 6 as-
tio
sign to the same variable price a string; at this point the vari-
a
type expression.
For example:
>>> 17 * 2.0
4
se
management of data. For example, some functions return as
lu
result values in string format (even when they are numbers),
while converting them to integers or floats may be necessary
na
to be able to use them for later calculations. The format func-
tio
tion, already seen, and the input function, which we will see
a
se
makes no sense or it is not technically feasible), an error mes-
lu
sage appears:
>>> int('Python')
na
tio
Traceback (most recent call last):
a
int('Python')
ed
>>> int(9.9999)
9
LEARNING PYTHON
se
Traceback (most recent call last):
lu
File "<pyshell#20>", line 1, in <module>
'€' + profit na
TypeError: can only concatenate str (not
tio
"float") to str
a
uc
verts the value of the profit variable into a string, thus allow-
ing its concatenation with the currency symbol:
or
-f
'€ 1227.64'
pl
m
For example:
se
>>> name = input('What is your name? ')
lu
What is your name?
na
tio
Once the user has typed a value and pressed the Enter key, the
function memorizes the piece of data in the name variable.
a
uc
>>> print(name)
or
Robert
-f
In the previous example we can notice the space after the ques-
e
tion mark in 'What is your name? ': if the space was not
pl
m
inserted, the user’s answer would not be divided from the ques-
Sa
<class 'str'>
This does not change if we decide to display the value
with print, even if the lack of quotes in the output may de- 4
ceive us. See the following example:
Once again, if we asked Python what the data type of the val-
ue variable is, we would get the same answer:
>>> type(value)
<class 'str'>
se
will get an error:
lu
>>> value = value + 1
Traceback (most recent call last): na
tio
File "<pyshell#16>", line 1, in <module>
value = value + 1
a
uc
se
Therefore, it is necessary to manage the output data of the in-
lu
put function, converting it into a float:
na
>>> side = float(input('What is the length of
tio
the side? '))
What is the length of the side? 3.5
a
uc
side * 4)
The perimeter of the square is: 14.0
e
pl