0% found this document useful (0 votes)
77 views

Capítulo 1 - Conceptos Básicos de Python

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views

Capítulo 1 - Conceptos Básicos de Python

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

CHAPTER

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.1 GETTING STARTED WITH PYTHON


1.1.1 SETTING UP YOUR WORKING ENVIRONMENT
The first step in using Python is to set up the working environment on the computer. This section
introduces the initial processes to get it started.
There are different ways to install Python and related packages, and we recommend using Ana-
conda1 or Miniconda2 to install and manage your packages. Depending on the operating system (OS)
you are using (i.e., Windows, Mac OS X, or Linux), you will need to download a specific installer for
your machine. Both Anaconda and Miniconda are aimed at providing easy ways to manage the Python
work environment in scientific computing and data sciences.

1 https://www.anaconda.com/download/.
2 https://conda.io/miniconda.html.

Python Programming and Numerical Methods. https://doi.org/10.1016/B978-0-12-819549-9.00010-5


Copyright © 2021 Elsevier Inc. All rights reserved.
3
4 CHAPTER 1 PYTHON BASICS

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.

1.1.2 THREE WAYS TO RUN PYTHON CODE


There are different ways to run Python code and they all have different usages. This section will intro-
duce the three different ways to get you started.
Using the Python shell or IPython shell. The easiest way to run Python code is through the Python
shell or IPython shell (which stands for Interactive Python). The IPython shell is more powerful than
the Python shell, including features such as Tab autocompletion, color-highlighted error messages, ba-
sic UNIX shell integration, and so on. Since we’ve just installed IPython, let us try to run the “Hello
World” example using it. To launch the IPython shell, we begin by typing ipython in a terminal (see
Fig. 1.6). Then we run a Python command by typing it into the shell and pressing Enter. We imme-
diately see the results from the command. For example, we can print out “Hello World” by using the
print function in Python, as shown in Fig. 1.6.
Run a Python script/file from the command line. The second way to run Python code is to put all
the commands into a file and save it as a file with the extension .py; the extension of the file can be
anything, but by convention, it is usually .py. For example, use your favorite text editor (here we used

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).

1.2 PYTHON AS A CALCULATOR


Python contains functions found in any standard graphing calculator. An arithmetic operation is either
addition, subtraction, multiplication, division, or powers between two numbers. An arithmetic opera-
tor is a symbol that Python has reserved to mean one of the aforementioned operations. These symbols
are + for addition, - for subtraction, * for multiplication, / for division, and ** for exponentiation.
An instruction or operation is executed when it is resolved by the computer. An instruction is
executed at the command prompt by typing it where you see the >>> symbol appears in the Python
shell (or the In [1]: sign in IPython) and then pressing Enter. In the case of the Jupyter notebook,
type the operation in the code cell and Shift + Enter. Since we will use Jupyter notebook for the
rest of the book, to familiarize yourself with all the different options, all examples in this section will
be shown in the IPython shell – see the previous section for how to begin working in IPython. For
Windows users, you will use the Anaconda prompt shown in the Appendix A instead of using the
terminal.
10 CHAPTER 1 PYTHON BASICS

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.

TRY IT! Compute the sum of 1 and 2.


In [1]: 1 + 2
Out[1]: 3

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)
.

In [2]: (3*4)/(2**2 + 4/2)


Out[2]: 2.0

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.

In [6]: import math

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.

TRY IT! Find the square root of 4.


In [7]: math.sqrt(4)
Out[7]: 2.0

TRY IT! Compute the sin( π2 ).


In [8]: math.sin(math.pi/2)
Out[8]: 1.0

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.

TRY IT! Compute elog 10 .


In [9]: math.exp(math.log(10))
Out[9]: 10.000000000000002

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.

TRY IT! 1/0.


In [12]: 1/0

----------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-12-9e1622b385b6> in <module>()
----> 1 1/0

ZeroDivisionError: division by zero

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

TRY IT! Compute ∞/∞.


In [15]: math.inf/math.inf
Out[15]: nan
14 CHAPTER 1 PYTHON BASICS

TRY IT! Compute sum 2 + 5i.


In [16]: 2 + 5j
Out[16]: (2+5j)

Note that in Python the imaginary part is represented by j instead of i.


Another way to represent a complex number in Python is to use the complex function.

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.

TRY IT! Find out the data type for 1234.


In [19]: type(1234)
Out[19]: int
1.3 MANAGING PACKAGES 15

TRY IT! Find out the data type for 3.14.


In [20]: type(3.14)
Out[20]: float

TRY IT! Find out the data type for 2 + 5j .


In [21]: type(2 + 5j)
Out[21]: complex

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.

1.3 MANAGING PACKAGES


One feature that makes Python really great is the various packages/modules developed by the user
community. Most of the time, when you want to apply some functions or algorithms, often you will
find multiple packages already available. All you need to do is to install the packages and use them
in your code. Managing packages is one of the most important skills you need to learn to take fully
advantage of Python. This section will show you how to manage packages in Python.

1.3.1 MANAGING PACKAGES USING PACKAGE MANAGERS


At the beginning of this book, we installed some packages using pip by typing pip install pack-
age_name. This is currently the most common and easy way to install Python packages. Pip is a package
manager that automates the process of installing, updating, and removing the packages. It can install
packages published on Python Package Index (PyPI).5 If you install Miniconda, pip will be available
for you to use as well.
Use pip help to get help for different commands, as shown in Fig. 1.12.
The most used commands usually include: installing, upgrading, and uninstalling a package.

Install a Package
To install the latest version of a package:
pip install package_name

To install a specific version, e.g., install version 1.5:

5 https://pypi.org/.
16 CHAPTER 1 PYTHON BASICS

FIGURE 1.12
The help document of pip after executing pip help.

pip install package_name==1.5

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

Other Useful Commands


Other useful commands that provide information about the installed packages are available. As shown
in Fig. 1.13, if you want to get a list of all the installed packages, you can use the command:
pip list

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

1.3.2 INSTALL PACKAGES FROM SOURCE


Occasionally, you will need to download the source file for some project that is not in the PyPI. In that
case, you need to install the package in a different way. In the standard install, after uncompressing the
file you downloaded, usually you can see the folder contains a setup script setup.py, and a file named
README, which documents how to build and install the module. For most cases, you just need to run
one command from the terminal to install the package:
python setup.py install

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.

1.4 INTRODUCTION TO JUPYTER NOTEBOOK


You have already used the IPython shell to run the code line by line. What if you have more lines and
want to run it block by block, and share it easily with others? In this case, the IPython shell is not a
good option. This section will introduce you another option, Jupyter notebook, which we will use for
the rest of the book. From the Jupyter notebook website7 :
The Jupyter notebook is an open-source web application that allows you to create and share docu-
ments that contain live code, equations, visualizations and narrative text. Uses include: data cleaning
and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and
much more.
Jupyter notebook runs using your browser; it can run locally on your machine as a local server
or remotely on a server. The reason it is called notebook is because it can contain live code, rich text
elements such as equations, links, images, tables, and so on. Therefore, you can have a very nice note-
book to describe your idea and the live code all in one document. Thus Jupyter notebook has become
a popular way to test ideas, write blogs, papers, and even books. In fact, this book was written entirely
within Jupyter notebook and converted to LaTeX afterwards. Although the Jupyter notebook has
many other advantages, to get you started we will only cover the basics here.

1.4.1 STARTING THE JUPYTER NOTEBOOK


As seen earlier, we can start Jupyter notebook by typing the following command in our terminal (for
Windows users, type this command in the Anaconda prompt) in the folder where you want to locate
the notebooks:
jupyter notebook

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.

1.4.2 WITHIN THE NOTEBOOK


After you create a new Python notebook, it will look like the one shown in Fig. 1.16. The toolbar and
menu are self-explanatory. If you hover the cursor over the toolbar, it will show you the function of the
tool. When you press the menu, it will show you the drop down list. Some important things to know
about the Jupyter notebook are as follows: a cell is the place you can write your code or text in. If
you run this cell, it only executes code within this cell block. Two important cell types are code and
markdown: (a) the code cell is where to type your code and where to run the code; (b) the markdown
cell is where to type the description in rich text format (see Fig. 1.16 as an example). Search for the
“Markdown cheatsheet” to get a quick start with markdown. To run the code or render the markdown
in the notebook is simple: press Shift + Enter.
The notebook allows you to move the cell up or down, insert or delete the cell, etc. There are many
other nice features available using Jupyter notebook, and we encourage you to access the many online
tutorials available to broaden your knowledge.
20 CHAPTER 1 PYTHON BASICS

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.

1.4.3 HOW DO I CLOSE A NOTEBOOK?


When you close the notebook browser tab, the notebook actually is not closed; it is still running in
the background. To completely close a notebook, go to the dashboard, and check the box before the
notebook. There is a shutdown option in the toolbar above; this is the correct way you close a notebook
completely.

1.4.4 SHUTTING DOWN THE JUPYTER NOTEBOOK SERVER


Closing the browser will not shut down the notebook server since it is still running. You can reopen the
previous address in a browser. To completely shut it down, we need to close the associated terminal
that you used to launch the notebook.
Now that you have the basic knowledge to launch and run a Jupyter notebook, you are equipped to
continue learning Python.

1.5 LOGICAL EXPRESSIONS AND OPERATORS


A logical expression is a statement that can either be true or false. For example, a < b is a logical
expression. It can be true or false depending on what values of a and b are given. Note that this
differs from a mathematical expression, which denotes a truth statement. In the previous example,
the mathematical expression a < b means that a is less than b, and values of a and b where a ≥ b are
not permitted. Logical expressions form the basis of computing. In this book all statements are assumed
to be logical rather than mathematical unless otherwise indicated.
1.5 LOGICAL EXPRESSIONS AND OPERATORS 21

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:

Table 1.1 Comparison operators.


Operator Description Example Results
> greather than a > b True
>= greater than or equal a >= b True
< less than a < b False
<= less than or equal a <= b False
!= not equal a != b True
== equal a == b False

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.

Table 1.2 Logical operators.


Operator Description Example Results
and greater than P and Q True if both P and Q are True. False otherwise
or greater than or equal P or Q True if either P or Q is True. False otherwise
not less than not P True if P is False. False if P is True

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:

In [3]: (1 and not 1) or (1 and 1)

Out[3]: 1

Now assume Q is false

In [4]: (1 and not 0) or (1 and 0)

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.

TRY IT! Compute (1 + 3) > (2 + 5)

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.

In [6]: (3 > 2) + (5 > 4)

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.

In [7]: (14*24*60*60) > 100000

Out[7]: True

1.6 SUMMARY AND PROBLEMS


1.6.1 SUMMARY
1. You have now learned the basics of Python, which should enable you to set up the working envi-
ronment and experiment with ways to run Python.
2. Python can be used as a calculator. It has all the functions and arithmetic operations commonly used
with a scientific calculator.
3. You can manage the Python packages using package managers.
4. You learned how to interact with Jupyter notebook.
5. You can also use Python to perform logical operations.
6. You have now been introduced to int, float, complex, string, and boolean data types in Python.

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

Use Ramanujan’s formula for N = 0 and N = 1 to approximate π. Compare your approximation


with Python’s stored value for π. Hint: 0! = 1 by definition.
12. The hyperbolic sin or sinh is defined in terms of exponentials as sinh(x) = exp(x)−exp(−x)
2 . Compute
sinh for x = 2 using exponentials. Verify that the result is indeed the hyperbolic sin using Python’s
function sinh in the math module.
13. Verify that sin2 (x) + cos2 (x) = 1 for x = π, π2 , π4 , π6 .
14. Compute the sin 87°.
15. Write a Python statement that generates the following error: “AttributeError: module ‘math’ has
no attribute ‘sni’.” Hint: sni is a misspelling of the function sin.
16. Write a Python statement that generates the following error: “TypeError: sin() takes exactly one
argument (0 given).” Hint: Input arguments refers to the input of a function (any function); for
example, the input in sin(π/2) is π/2.
17. If P is a logical expression, the law of noncontradiction states that P AND (NOT P) is always false.
Verify this for P true and P false.
1.6 SUMMARY AND PROBLEMS 25

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:

e2 sin π/6 + loge (3) cos π/9 − 53 .

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).

You might also like