Capítulo 1 - Conceptos Básicos de Python
Capítulo 1 - Conceptos Básicos de Python
PYTHON BASICS
1
CONTENTS
1.1 Getting Started With Python ......................................................................................... 3
1.1.1 Setting Up Your Working Environment ............................................................. 3
1.1.2 Three Ways to Run Python Code .................................................................... 7
1.2 Python as a Calculator ............................................................................................... 9
1.3 Managing Packages .................................................................................................. 15
1.3.1 Managing Packages Using Package Managers .................................................... 15
Install a Package ............................................................................................. 15
Upgrade a Package.......................................................................................... 16
Uninstall a Package.......................................................................................... 16
Other Useful Commands ................................................................................... 16
1.3.2 Install Packages From Source ....................................................................... 18
1.4 Introduction to Jupyter Notebook ................................................................................... 18
1.4.1 Starting the Jupyter Notebook....................................................................... 18
1.4.2 Within the Notebook .................................................................................. 19
1.4.3 How Do I Close a Notebook?......................................................................... 20
1.4.4 Shutting Down the Jupyter Notebook Server ...................................................... 20
1.5 Logical Expressions and Operators ................................................................................ 20
1.6 Summary and Problems .............................................................................................. 23
1.6.1 Summary ............................................................................................... 23
1.6.2 Problems ............................................................................................... 23
1 https://www.anaconda.com/download/.
2 https://conda.io/miniconda.html.
FIGURE 1.1
The Miniconda download page; choose the installer based on your operating system.
In this example, we will use Mac OS X to show you how to install Miniconda (the process of which
is very similar to installing on Linux). For Windows users, please skip the rest of this section and read
Appendix A on the installation instructions. The main differences between Anaconda and Miniconda
are as follows:
• Anaconda is a complete distribution framework that includes the Python interpreter, package man-
ager, and the commonly used packages in scientific computing.
• Miniconda is a “light” version of Anaconda that does not include the commonly used packages.
You need to install all the different packages yourself, but it does include the Python interpreter and
package manager.
The option we’ve chosen here is Miniconda, and we will install only those packages that we will
need. The Miniconda install process is described below:
Step 1. Download the Miniconda installer from the website.3 The download page is shown in
Fig. 1.1. Here you can choose a different installer based on your OS. In this example, we choose Mac
OS X and Python 3.7.
Step 2. Open a terminal (on a Mac, you can search for “terminal” in Spotlight search). Run the
installer from the terminal using the commands showing in Fig. 1.2. After you run the installer, follow
the guide to finish the installation.
Note that although you can change the installation location by giving it an alternative location on
your machine, the default is your home directory (Fig. 1.3).
After installation, you can check the installed packages by typing the commands shown in Fig. 1.4.
3 https://conda.io/miniconda.html.
1.1 GETTING STARTED WITH PYTHON 5
FIGURE 1.2
Screen shot of running the installer in a terminal.
FIGURE 1.3
The default installation location of your file system.
6 CHAPTER 1 PYTHON BASICS
FIGURE 1.4
Quick way to check if Miniconda was installed successfully and the programs are run properly.
FIGURE 1.5
Installation process for the packages that will be used in the rest of the book.
1.1 GETTING STARTED WITH PYTHON 7
Step 3. As shown in Fig. 1.5, install the basic packages used in this book: ipython, numpy, scipy,
pandas, matplotlib, and jupyter notebook. In a later section, we will talk about the management of
the packages using pip and conda.
FIGURE 1.6
Run “Hello World” in IPython shell by typing the command. “print” is a function that is discussed later in the book
that will print out anything within the parentheses.
8 CHAPTER 1 PYTHON BASICS
FIGURE 1.7
Example of a Python script file example using Visual Studio Code. Type in the commands you want to execute and
save the file with a proper name.
FIGURE 1.8
To run the Python script from command line, type “python hello_world.py”. This line tells Python to execute the
commands that saved in this file.
Visual Studio Code4 ) to type the commands you wish to execute in a file called hello_world.py, as
shown in Fig. 1.7, which is then run from terminal (see Fig. 1.8).
4 https://code.visualstudio.com.
1.2 PYTHON AS A CALCULATOR 9
FIGURE 1.9
To launch a Jupyter notebook server, type jupyter notebook in the command line, which will open a browser
page as shown here. Click the “New” button on the top right and choose “Python3”. This will create a Python
notebook from which to run Python code.
Using Jupyter Notebook. The third way to run Python is through Jupyter Notebook, which is a very
powerful browser-based Python environment. We will discuss this in details later in this chapter. The
example presented here is to demonstrate how quickly we can run the code using Jupyter notebook.
If you type jupyter notebook in the terminal, a local web page will pop up; use the upper right button
to create a new Python3 notebook, as shown in Fig. 1.9.
Running code in Jupyter notebook is easy. Type your code in the cell and press Shift + Enter
to run the cell; the results will be shown below the code (Fig. 1.10).
FIGURE 1.10
To run the Hello World example within Jupyter notebook, type the command in the code cell (the grey boxes) and
press Shift + Enter to execute it.
An order of operations is a standard order of precedence that different operations have in re-
lationship to one another. Python utilizes the same order of operations you learned in grade school.
Powers are executed before multiplication and division, which are executed before addition and
subtraction. Parentheses ( ) can also be used in Python to supersede the standard order of opera-
tions.
3×4
TRY IT! Compute (22 +4/2)
.
TIP! Note that Out[2] is the resulting value of the last operation executed. Use the underscore
symbol _ to represent this result to break up complicated expressions into simpler commands.
1.2 PYTHON AS A CALCULATOR 11
TRY IT! Compute 3 divided by 4, then multiply the result by 2, and then raise the result to the
3rd power.
In [3]: 3/4
Out[3]: 0.75
In [4]: _*2
Out[4]: 1.5
In [5]: _**3
Out[5]: 3.375
Python has many basic arithmetic functions like sin, cos, tan, asin, acos, atan, exp, log, log10,
and sqrt stored in a module (explained later in this chapter) called math. First, import this module to
access to these functions.
TIP! In Jupyter notebook and IPython, you can have a quick view of what is in the module
by typing the module name + dot + TAB. Furthermore, if you type the first few letters of the
function and press TAB, it will automatically complete the function, which is known as “TAB
completion” (an example is shown in Fig. 1.11).
These mathematical functions are executed via module.function. The inputs to them are always
placed inside of parentheses that are connected to the function name. For trigonometric functions, it is
useful to have the value of π available. You can call this value at any time by typing math.pi in the
IPython shell.
Python composes functions as expected, with the innermost function being executed first. The same
holds true for function calls that are composed with arithmetic operations.
12 CHAPTER 1 PYTHON BASICS
FIGURE 1.11
An example demonstrating the interactive search for functions within IPython by typing TAB after the dot. The grey
box shown all available functions.
Note that the log function in Python is loge , or the natural logarithm. It is not log10 . To use log10 ,
use the function math.log10.
TIP! You can see the result above should be 10, but in Python, it shows as 10.000000000000002.
This is due to Python’s number approximation, discussed in Chapter 9.
3
TRY IT! Compute e 4 .
In [10]: math.exp(3/4)
Out[10]: 2.117000016612675
TIP! Using the UP ARROW in the command prompt recalls previously executed commands that
were executed. If you accidentally type a command incorrectly, you can use the UP ARROW to
recall it, and then edit it instead of retyping the entire line.
Often when using a function in Python, you need help specific to the context of the function. In
IPython or Jupyter notebook, the description of any function is available by typing function?; the
1.2 PYTHON AS A CALCULATOR 13
question mark is a shortcut for help. If you see a function you are unfamiliar with, it is good practice
to use the question mark before asking your instructors what a specific function does.
TRY IT! Use the question mark to find the definition of the factorial function.
In [11]: math.factorial?
Signature: math.factorial(x, /)
Docstring:
Find x!.
Raise a ValueError if x is negative or non-integral.
Type: builtin_function_or_method
Python will raise an ZeroDivisionError when the expression 1/0 (which is infinity) appears, to
remind you.
----------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-12-9e1622b385b6> in <module>()
----> 1 1/0
You can type math.inf at the command prompt to denote infinity or math.nan to denote something
that is not a number that you wish to be handled as a number. If this is confusing, this distinction can be
skipped for now; it will be explained in detail later. Finally, Python can also handle imaginary numbers.
TRY IT! Type 1/∞, and ∞ ∗ 2 to verify that Python handles infinity as you would expect.
In [13]: 1/math.inf
Out[13]: 0.0
In [14]: math.inf * 2
Out[14]: inf
In [17]: complex(2,5)
Out[17]: (2+5j)
Python can also handle scientific notation using the letter e between two numbers. For example,
1e6 = 1000000 and 1e − 3 = 0.001.
TRY IT! Compute the number of seconds in 3 years using scientific notation.
In [18]: 3e0*3.65e2*2.4e1*3.6e3
Out[18]: 94608000.0
TIP! Every time a function in math module is typed, it is always typed math.function_name.
Alternatively, there is a simpler way. For example, if we want to use sin and log from math
module, we can import them as follows: from math import sin, log. With this modified import
statement, when using these functions, use them directly, e.g., sin(20) or log(10).
The previous examples demonstrated how to use Python as a calculator to deal with different data
values. In Python, there are additional data types needed for numerical values: int, float, and complex
are the types associated with these values.
• int: Integers, such as 1, 2, 3, . . .
• float: Floating-point numbers, such as 3.2, 6.4, . . .
• complex: Complex numbers, such as 2 + 5j, 3 + 2j, . . .
Use function type to check the data type for different values.
Of course, there are other data types, such as boolean, string, and so on; these are introduced in
Chapter 2.
This section demonstrated how to use Python as a calculator by running commands in the IPython
shell. Before we move on to more complex coding, let us go ahead to learn more about the managing
packages, i.e., how to install, upgrade, and remove the packages.
Install a Package
To install the latest version of a package:
pip install package_name
5 https://pypi.org/.
16 CHAPTER 1 PYTHON BASICS
FIGURE 1.12
The help document of pip after executing pip help.
Pip will install the package as well as the other dependent packages for you to use.
Upgrade a Package
To upgrade an installed package to the latest version from PyPI.
pip install --upgrade package_name
or simply
pip install -U package_name
Uninstall a Package
pip uninstall package_name
If you want to know more about an installed package, such as the location of the package, the
required other dependent packages, etc., you can use the following command as shown in Fig. 1.14:
pip show package_name
1.3 MANAGING PACKAGES 17
FIGURE 1.13
Using pip list to show all the packages installed on your machine.
FIGURE 1.14
Using pip show to get detailed information about a installed package.
Other package managers exist, e.g., conda (which is included with the Anaconda distribution and
is similar to pip in terms of its capability); therefore, it is not discussed further, and you can find more
information by reading the documentation.6
6 https://conda.io/docs/user-guide/getting-started.html.
18 CHAPTER 1 PYTHON BASICS
Note that Windows users will need to run the following command from a command prompt window:
setup.py install
Now you know how to manage the packages in Python, which is a big step forward in using Python
correctly. In the next section, we will talk more about the Jupyter notebook that we used for the rest
of the book.
7 http://jupyter.org/.
1.4 INTRODUCTION TO JUPYTER NOTEBOOK 19
FIGURE 1.15
The Jupyter notebook dashboard after launching the server. Red arrows (light grey arrows in print version) are
pointing to you the most common features in the dashboard.
The Jupyter notebook dashboard will appear in the browser as shown in Fig. 1.15. The default
address is: http://localhost:8888, which is at the localhost with port 8888, as shown in Fig. 1.15 (if
the port 8888 is taken by other Jupyter notebooks, then it will automatically use another port). This
is essentially creating a local server to run in your browser. When you navigate to the browser, you
will see a dashboard. In this dashboard, you will see some important features labeled in red (light grey
in print version). To create a new Python notebook, select “Python 3,” which is usually called Python
kernel. You can use Jupyter to run other kernels as well. For example, in Fig. 1.15, there are Bash and
Julia kernels that you can run as a notebook, but you will need to install them first. We will use the
Python kernel, so choose Python 3 kernel.
FIGURE 1.16
A quick view of a notebook. The Header of the notebook shows the name of the notebook. The menu has vari-
ous drop-down lists that let you access to all the functionalities of the notebook. The tool bar provides you some
shortcuts for the commonly used functionalities.
In Python, a logical expression that is true will compute to the value True. A false expression
will compute to the value False. This is a new data type known as boolean, which has the built-in
values True and False. In this book, “True” is equivalent to 1, and “False” is equivalent to 0. Logical
expressions are used to pose questions to Python. For example, “3 < 4” is equivalent to, “Is 3 less than
4?” Since this statement is true, Python will compute it as 1; however, if we write 3 > 4, this is false,
and Python will compute it as 0.
Comparison operators compare the value of two numbers, which are used to build logical expres-
sions. Python reserves the symbols >, >=, <, <=, ! =, ==, to denote “greater than,” “greater than or
equal,” “less than,” “less than or equal,” “not equal,” and “equal,” respectively; see and Table 1.1. Let
us start with an example, a = 4, b = 2:
TRY IT! Compute the logical expression for “Is 5 equal to 4?” and “Is 2 smaller than 3?”
In [1]: 5 == 4
Out[1]: False
In [2]: 2 < 3
Out[2]: True
Logical operators, as shown in Table 1.2, are operations between two logical expressions that, for
the sake of discussion, we will call P and Q. The fundamental logical operators we will use herein are
and, or, and not.
The truth table, as shown in Fig. 1.17, of a logical operator or expression gives the result of every
truth combination of P and Q. Fig. 1.17 shows the truth tables for “and” and “or”.
22 CHAPTER 1 PYTHON BASICS
FIGURE 1.17
Truth tables for the logical and/or.
TRY IT! Assuming P is true, let us use Python to determine if the expression (P AND NOT(Q))
OR (P AND Q) is always true regardless of whether or not Q is true. Logically, can you see why
this is the case? First assume Q is true:
Out[3]: 1
Out[4]: True
Just as with arithmetic operators, logical operators have an order of operations relative to each other
and in relation to arithmetic operators. All arithmetic operations will be executed before comparison
operations, which will be executed before logical operations. Parentheses can be used to change the
order of operations.
In [5]: 1 + 3 > 2 + 5
Out[5]: False
TIP! Even when the order of operations is known, it is usually helpful for you and those reading
your code to use parentheses to make your intentions clearer. In the preceding example (1 + 3) >
(2 + 5) is clearer.
1.6 SUMMARY AND PROBLEMS 23
WARNING! In Python’s implementation of logic, 1 is used to denote true and 0 for false. But
because 1 and 0 are still numbers, Python will allow abuses such as: (3 > 2) + (5 > 4), which will
resolve to 2.
Out[6]: 2
WARNING! Although in formal logic 1 is used to denote true and 0 to denote false, Python’s
notation system is different, and it will take any number not equal to 0 to mean true when used
in a logical operation. For example, 3 and 1 will compute to true. Do not utilize this feature of
Python. Always use 1 to denote a true statement.
TIP! A fortnight is a length of time consisting of 14 days. Use a logical expression to determine
if there are more than 100,000 seconds in a fortnight.
Out[7]: True
1.6.2 PROBLEMS
1. Print “I love Python” using Python Shell.
2. Print “I love Python” by typing it into a .py file and run it from command line.
3. Type import antigravity in the IPython Shell, which will take you to xkcd and enable you to
see the awesome Python.
4. Launch a new Jupyter notebook server in a folder called “exercise” and create a new Python
notebook with the name “exercise_1.” Put the rest of the problems within this notebook.
24 CHAPTER 1 PYTHON BASICS
5. Compute the area of a triangle with base 10 and height 12. Recall that the area of a triangle is half
the base times the height.
6. Compute the surface area and volume of a cylinder with radius 5 and height 3.
7. Compute the slope between the points (3, 4) and (5, 9). Recall that the slope between points
(x1 , y1 ) and (x2 , y2 ) is yx22 −y1
−x1 .
8. Compute the distancebetween the points (3, 4) and (5, 9). Recall that the distance between points
in two dimensions is (x2 − x1 )2 + (y2 − y1 )2 .
9. Use Python’s factorial function to compute 6!
10. Although a year is considered to be 365 days long, a more exact figure is 365.24 days. As a
consequence, if we held to the standard 365-day year, we would gradually lose that fraction of the
day over time, and seasons and other astronomical events would not occur as expected. To keep
the timescale on tract, a leap year is a year that includes an extra day, February 29, to keep the
timescale on track. Leap years occur on years that are exactly divisible by 4, unless it is exactly
divisible by 100, unless it is divisible by 400. For example, the year 2004 is a leap year, the year
1900 is not a leap year, and the year 2000 is a leap year. Compute the number of leap years between
the years 1500 and 2010.
11. A very powerful approximation for π was developed by a brilliant mathematician named Srinivasa
Ramanujan. The approximation is the following:
√ N
1 2 2 (4k)!(1103 + 26390k)
≈ .
π 9801 (k!)4 3964k
k=0
FIGURE 1.18
Truth tables for the logical XOR.
18. Let P and Q be logical expressions. De Morgan’s rule states that NOT (P OR Q) = (NOT P ) AND
(NOT Q) and NOT (P AND Q) = (NOT P ) OR (NOT Q). Generate the truth tables for each
statement to show that De Morgan’s rule is always true.
19. Under what conditions for P and Q is (P AND Q) OR (P AND (NOT Q)) false?
20. Construct an equivalent logical expression for OR using only AND and NOT.
21. Construct an equivalent logical expression for AND using only OR and NOT.
22. The logical operator XOR has the following truth table: Construct an equivalent logical expression
for XOR using only AND, OR, and NOT that has the same truth table (see Fig. 1.18).
23. Do the following calculation at the Python command prompt:
24. Do the following logical and comparison operations at the Python command prompt. You may
assume that P and Q are logical expressions. For P = 1 and Q = 1, compute NOT(P ) AND
NOT(Q). For a = 10 and b = 25, compute (a < b) AND (a = b).