Get (Ebook) An Introduction to Python Programming for Scientists and Engineers by Johnny Wei-Bing Lin, Hannah Aizenman, Erin Manette Cartas Espinel, Kim Gunnerson, Joanne Liu ISBN 9781108701129, 1108701124 PDF ebook with Full Chapters Now
Get (Ebook) An Introduction to Python Programming for Scientists and Engineers by Johnny Wei-Bing Lin, Hannah Aizenman, Erin Manette Cartas Espinel, Kim Gunnerson, Joanne Liu ISBN 9781108701129, 1108701124 PDF ebook with Full Chapters Now
com
OR CLICK HERE
DOWLOAD EBOOK
ebooknice.com
ebooknice.com
https://ebooknice.com/product/sat-ii-success-
math-1c-and-2c-2002-peterson-s-sat-ii-success-1722018
ebooknice.com
ebooknice.com
(Ebook) Cambridge IGCSE and O Level History Workbook 2C -
Depth Study: the United States, 1919-41 2nd Edition by
Benjamin Harrison ISBN 9781398375147, 9781398375048,
1398375144, 1398375047
https://ebooknice.com/product/cambridge-igcse-and-o-level-history-
workbook-2c-depth-study-the-united-states-1919-41-2nd-edition-53538044
ebooknice.com
https://ebooknice.com/product/prototyping-python-dashboards-for-
scientists-and-engineers-55888336
ebooknice.com
ebooknice.com
https://ebooknice.com/product/fiber-optic-sensors-an-introduction-for-
engineers-and-scientists-4643872
ebooknice.com
An Introduction to Python Programming for
Scientists and Engineers
Python is one of the most popular programming languages, widely used for data analysis
and modelling, and is fast becoming the leading choice for scientists and engineers. Unlike
other textbooks introducing Python, typically organised by language syntax, this book uses
many examples from across Biology, Chemistry, Physics, Earth science, and Engineering to
teach and motivate students in science and engineering. The text is organised by the tasks
and workflows students undertake day-to-day, helping them see the connections between
programming tools and their disciplines. The pace of study is carefully developed for complete
beginners, and a spiral pedagogy is used so concepts are introduced across multiple chapters,
allowing readers to engage with topics more than once. “Try This!” exercises and online
Jupyter notebooks encourage students to test their new knowledge, and further develop their
programming skills. Online solutions are available for instructors, alongside discipline-specific
homework problems across the sciences and engineering.
Hannah Aizenman is a Ph.D. candidate in Computer Science at The Graduate Center, City
University of New York. She studies visualization and is a core developer of the Python
library Matplotlib.
Erin Manette Cartas Espinel graduated with a Ph.D. in physics from the University of
California, Irvine. After more than 10 years at the University of Washington Bothell, she
is now a software development engineer.
Joanne Liu received her Ph.D. in Bioinformatics and Systems Biology from the University of
California San Diego.
“This book provides an excellent introduction to the Python language especially targeted at those
interested in carrying out calculations in the physical sciences. I especially like the strong coverage of
graphics and of good coding practice.”
Raymond Pierrehumbert, University of Oxford
“An excellent introduction to Python for scientists and engineers. Much more than teaching you how to
program with Python, it teaches you how to do science with Python.”
Eric Shaffer, University of Illinois at Urbana-Champaign
“Python has achieved an essential role in many disciplines within science, engineering, and beyond.
Students and professionals are expected to be fluent in it, and (as I see in my daily job of helping users of a
high-performance computing facility) they often struggle to reach that fluency. The authors have succeeded
in the daunting task of writing a single book to help people reach a very advanced level of fluency, starting
very gently and assuming no background. Unlike other books on the subject, An Introduction to Python
Programming for Scientists and Engineers focuses on teaching for the intended end goal of scientists and
engineers – investigating their scientific problems – not writing software for its own sake. I am looking
forward to working with the generation who will learn how to program in Python using this book!”
Davide Del Vento, NCAR Computational & Information Services Laboratory
“An Introduction to Python Programming for Scientists and Engineers introduces programming in Python
using evidence-based approaches to active learning. The exercises help both students and instructors
identify misconceptions in programming, allowing students to build a strong foundation in Python
programming. The book streamlines content such that there is a focus on mastering immediately useful
concepts, normalizing errors, and demonstrating recovery.”
Kari L. Jordan, Executive Director, The Carpentries
An Introduction to Python
Programming for Scientists
and Engineers
Hannah Aizenman
City College of New York
Kim Gunnerson
University of Washington Bothell
Joanne Liu
Novozymes A/S
University Printing House, Cambridge CB2 8BS, United Kingdom
www.cambridge.org
Information on this title: www.cambridge.org/highereducation/isbn/9781108701129
DOI: 10.1017/9781108571531
A catalogue record for this publication is available from the British Library.
v
vi Contents
20 Recursion 633
Glossary 719
Acronyms and Abbreviations 726
Bibliography 727
Index 729
Detailed Contents
vii
viii Detailed Contents
20 Recursion 633
20.1 Example of Recursion 633
20.2 Python Programming Essentials 635
20.2.1 Using the walk Generator 635
20.2.2 Recursion and Writing Recursive Code 637
20.2.3 More Applications of Recursion 642
20.3 Try This! 645
20.4 More Discipline-Specific Practice 649
20.5 Chapter Review 649
20.5.1 Self-Test Questions 649
20.5.2 Chapter Summary 650
20.5.3 Self-Test Answers 651
Glossary 719
Acronyms and Abbreviations 726
Bibliography 727
Index 729
Preface
Most introductory programming textbooks are written with the assumption that the student
thinks like a computer scientist. That is, writers assume that the student best learns pro-
gramming by focusing on the structure and syntax of programming languages. The result
is an introductory textbook that teaches programming in a way that is accessible to future
programmers and developers but not as much to scientists or engineers who mainly want to
investigate scientific problems.
This textbook is written to teach programming to scientists and engineers, not to computer
scientists. We assume that the reader has no background, formal or informal, in computer pro-
gramming. Thus, this textbook is distinct from other introductory programming textbooks
in the following ways:
• It is organized around a scientist or engineer’s workflow. What are the tasks of a scientist
or engineer that a computer can help with? Doing calculations (e.g., Chapters 2 and 6),
making a plot (e.g., Chapters 4 and 5), handling missing data (e.g., Chapter 15), and saving
and storing data (e.g., Chapters 9 and 18) are just a few of the tasks we address.
• It teaches programming, not numerical methods, statistics, data analytics, or image process-
ing. The level of math that the reader needs is modest so the text is accessible to a first-year
college student.
• It provides examples pertinent to the natural sciences and engineering. Jupyter notebooks
associated with this textbook provide structured practice using examples from physics,
chemistry, and biology, and additional notebooks for engineering are planned. For instance,
the physics notebooks include problems dealing with electromagnetic fields, optics, and
gravitational acceleration.
• Syntax is secondary. The primary goal is to teach the student how to use Python to do
scientific and engineering work. Thus, we teach as much language syntax and structure as
needed to do a task. Later, as we address more complex science and engineering tasks, we
teach additional aspects of language syntax and structure. As a result, this textbook is not
intended as a Python language reference where all (or most) of the aspects of a given feature
of the language are addressed at the same time.
• It is paced for the beginner. This text offers many examples, explanations, and opportunities
to practice. We take things slowly because learning is a step-by-step process, not a toss-into-
the-deep-end process. As a result, this text is not concise, particularly in the beginning. It
will seem ponderous to an expert programmer. This is intentional.
xvii
xviii Preface
example nor to exercises in a Jupyter notebook, the chapters in Part IV are not organized
using the five-section pattern most of the chapters in Parts I–III use. The aim of Part IV is
to introduce software engineering tools and practices that help us to write better and more
reliable code, in order for the reader to seek more information in works that specialize in
these topics. We hope that our introduction will whet your appetite to learn more on your
own about these tools and practices.
When we first start to learn something, we require more explanation and practice to get
comfortable with the material, learn the vocabulary, and think in new ways. The textbook is
thus structured like a pyramid:
More Repetitive
The chapters in Part I are the longest, and the chapters in Part IV are the shortest. The
earlier parts are more repetitive and less concise while the later parts are less repetitive and
more concise. The wider the block in the pyramid above, the more repetitive the part. The
higher up the pyramid, the more concise the part.
a given chapter, because we do not fully describe that structure in that chapter, the code
examples may seem awkward and more complicated than needed. Second, by spreading out
the description of a single structure over multiple chapters, this textbook does not function
well as a reference. What can you do to mitigate these costs? For the first, we ask for your
patience as we slowly build up the description of the topic. The code examples will become
more concise and Pythonic as the book progresses. For the second, we have written the
textbook to provide a substantial amount of cross-referencing between sections, so those
cross-references might be enough to lead you where you want to go. Skimming the Detailed
Contents, which details the subtopics included in each chapter, or Index, may also help you
find the occurrences of the topics you are interested in. Appendix C also lists the contents
of the book by programming topic.
• The “how to write a program” chapter does not come early on as it does in most
programming textbooks. We briefly mention how to write programs in Section 6.2.7 and
provide a more detailed treatment in Chapter 11. How come? If the goal of the textbook is
to teach programming by doing, rather than reading about how to “do,” it should start off
with using Python to do science and engineering tasks. Once the reader has some experience
writing short programs, they will have more context to understand advice on how to write
a longer program.
• The workflow focus influences how looping and branching are introduced in this textbook.
In most textbooks, these topics are introduced separately, in separate chapters. The result,
however, is to limit what can be done with such knowledge. An if statement by itself,
without the possibility of being visited multiple times, does not accomplish much. In this
textbook, we introduce both concepts together, in Chapter 6 on basic diagnostic data
analysis. Neither topic is treated exhaustively in this chapter, but with the introduction of
both topics in one chapter, we can vividly show how useful these structures are for using
the computer to investigate a dataset.
• Because the textbook is aimed at novices rather than students with programming experi-
ence, we had to make difficult choices regarding what concepts to introduce and when.
One result of these choices is that, particularly in earlier chapters, our code examples
are less than Pythonic in order to make our treatment of the concepts at that point in
the book clearer to novice students. We also ignore some packages and tools that can
accomplish some of the tasks we address more concisely and efficiently, in order to focus
on the learning goal at hand. Reasonable people will disagree regarding our choices, but
we wanted instructors to know we recognize the tension, and we heartily support whatever
customization will best meet the needs of your students.
• Parts I–II are material for approximately one semester-long (15 week) introductory pro-
gramming course.
• Parts I–III are written so later chapters build on the contents of earlier chapters. They
contain material for a two-quarter introductory programming sequence.
• The chapters in Part IV are supplemental and can be read independently and used for self-
study.
• Going in order is one way to use the textbook. However, other sequences are possible. For
instructors who want to cover the material by programming topic, the table of contents in
Appendix C shows where various aspects of the programming topics are covered.
• Try This! exercises are designed to provide practice for students to take bite-sized, incre-
mental steps in growing their understanding the material. In a classroom setting, they are
appropriate for active learning problems, group work, and as components in programming
labs. The answers are publicly available, so these exercises are best used for practice and
development rather than summative assessment.
• The Homework Problems are provided online as Jupyter notebooks and require more
time for students to work on than the Try This!. Thus, generally speaking, they are more
appropriate for students to work on outside of class. Solutions for homework notebooks
are only provided to verified instructors.
The “To the Student” section following this Preface provides further description of the kinds
of exercises and problems that are available.
All the above resources (with the exception of the images, and solutions for exercises and
problems) are accessible by both students and instructors.
The landscape of Python teaching resources is vast and constantly changing. We
provide a web page listing some of these resources at www.cambridge.org/core/resources/
pythonforscientists/instructors/.
Please let us know of any corrections by emailing us at [email protected].
To the Student
An Introduction to Python Programming for Scientists and Engineers consists of two compo-
nents:
• The print/digital book that you are now reading.
• Online resources including web pages with additional content and exercises and problems
as Jupyter notebooks.
The latter are not “supplements” because they tightly link to the content and flow of the
textbook. The two pieces form an integrated whole.
xxiii
xxiv To the Student
The larger datasets referenced in this textbook and the Jupyter notebooks are found at
www.cambridge.org/core/resources/pythonforscientists/datasets/. These are freely available
for download.
changes. When we encounter code, we should ask how the program would behave differently
if we made a change to the values and order of the code. And we should take notes (by hand, if
possible, because we learn more that way) on what we have read and write down any questions
we have as they come to us. If we do not write down questions immediately, we will forget
them and falsely believe we understand the material. We have to actively engage the text.
We cannot read a programming textbook (or any math, science, or engineering textbook) as
if it were a novel. When we read a novel, we can just read the words and sentences themselves,
skimming if we are in a rush. The prose itself tells us about the characters, plot, and setting.
But in a programming textbook, this kind of reading will not work. Skimming a programming
textbook is a recipe for disaster. We have to unpack and excavate the meaning of the code
and the text describing the code. If we do not, our understanding will be limited. So, read
s-l-o-w-l-y!
Notices and Disclaimers
Copyright Acknowledgments
Screenshots of Chrome browser sessions (e.g., Figures 2.3, 3.7, 3.8, 3.9, 4.6, and 4.7) include
elements from Google LLC and are used by permission.
Images from Volkman et al. (2004) in Chapter 13 are copyright © 2004 by Volkman
et al. and are used by permission under the conditions of the Creative Commons Attribution
License. Volkman et al. do not specify the license version, but the Creative Commons
1 www.jetbrains.com.
xxvi
Notices and Disclaimers xxvii
Section 13.3 includes images from Patel and Dauphin (2019), published by NASA’s Earth
Observatory, which were created using Black Marble data from Ranjay Shrestha at NASA’s
Goddard Space Flight Center and Landsat data from the U.S. Geological Survey.
World Time Buddy (www.worldtimebuddy.com) provided help with time zone conversions.
(See Sections 7.1 and 12.1.)
Data used for displaying natural features and political boundries (in Chapter 14)
are provided by OpenStreetMap (© OpenStreetMap contributors) and Natural Earth
(public domain). OpenStreetMap data are available under the Open Database Licence
(www.openstreetmap.org/copyright). Free vector and raster map data are available at
naturalearthdata.com.
Data in this work are also acknowledged in descriptions in the main text and footnotes. All
data and images in this work are used by permission. Many of these materials are in the public
domain or are otherwise freely available for republication and reuse. Please see the sources of
the data for details.
Data presented in this work that are not explicitly attributed to a source should be
considered fictional and created by the authors for the purposes of illustration or teaching.
They must not be considered genuine or accurate descriptions of any natural or artificial
phenomena or system. Most (though not all) occurrences of such data are accompanied by
the term “fictitious” or “pretend.”
Disclaimers
Although we have worked hard to make the text, code, and related online resources (together,
“Resources”) accurate and correct, the Resources are provided “as-is,” without warranty of
any kind, express or implied, including but not limited to the warranties of merchantability,
fitness for a particular purpose and noninfringement. In no event shall the authors or
copyright holders be liable for any claim, damages or other liability, whether in an action
of contract, tort or otherwise, arising from, out of or in connection with the Resources or the
use or other dealings in the Resources.3
Permission to use marks, trademarks, copyrighted materials, or any other materials by their
owners does not imply an endorsement of that use or of the Resources.
3 Copied and adapted from the MIT License, as listed on Opensource.org, https://opensource.org/licenses/MIT
We are grateful for the editorial help of Charles Howell, Matt Lloyd, Lisa Pinto, and Melissa
Shivers at Cambridge University Press. We thank Spencer Cotkin for editorial suggestions,
most we have implemented and that have made the book much better. We thank Beverley
Lawrence for copyediting the text. A number of anonymous reviewers provided helpful
feedback which have been incorporated into the text.
We are thankful for Cynthia Gustafson-Brown’s assistance on this project, particularly in
finding and providing some of the description in the Section 13.1 example.
We are appreciative of conversations with and assistance by: Bill Erdly, Michael Grossberg,
Charity Flener Lovitt, Laurence Molloy, Hansel Ong, Jim Phillips, and Rob Nash. Whether
through publications, workshops, conferences, or discussions, the communities we are a part
of – personal, workplace, disciplinary, and, of course, the Python community – contributed
ideas, encouragement, and support.
Parts of this book are based on the book, A Hands-On Introduction to Using Python in the
Atmospheric and Oceanic Sciences,4 slides from the 2020 American Meteorological Society’s
Beginner’s Course to Using Python in Climate and Meteorology,5 and the set of notes, Lecture
Notes on Programming Theory for Management Information Systems.6 These resources are
by Johnny Lin and the acknowledgments made in those resources also apply to this text.
We are grateful for those who gave us permission to use material they created. These are
acknowledged in the Notices section, the captions of the included or adapted figures, or in
the online resources.
4 Lin (2012).
5 Not formally published.
6 Lin (2019).
xxix
xxx Acknowledgments
I thank my wife Karen, and my children Timothy, James, and Christianne for their
encouragement and love. S.D.G.
Johnny Wei-Bing Lin
Bellevue, Washington
I thank my advisor, Professor Michael Grossberg, for all his help and the AMS Python
community and Matplotlib Development Team for their influence and conversations on all
things code.
Hannah Aizenman
New York City, New York
I thank my husband Vicente, my family Duffy, Cheryl, and Sara, and my friends Valerine,
Kaitlyn, and Alanna for all of their love and support.
Erin Manette Cartas Espinel
Kenmore, Washington
I thank Samantha Gunnerson for her help reading through notebooks to give me advice,
Eric Gunnerson for his support as well as technical skills, and Dr. Paola Rodríguez Hidalgo
for listening to me talk about the different Python writing I was doing during this process.
Kim Gunnerson
Bellevue, Washington
I thank my family for their support and Cynthia Gustafson-Brown for providing several
of the More Discipline-Specific Practice problems in Chapters 2 and 3.
Joanne Liu
San Diego, California
Part I
The Preface and To the Student sections describe how and why we structured the book and
resources the way we did and how to make the most out of them. In the present chapter, we
set the stage for the study of programming as an endeavor and Python as a language. We also
describe what software needs to be installed in order to make use of the rest of the book.
3
4 1 Prologue: Preparing to Program
calculations without calculators, let alone computers. Today, great science and engineering
work can still be done without needing to program a computer. For work involving small
datasets or analytical mathematical solutions, pen and paper (and a calculator or spreadsheet)
is often enough.
Today, however, we enjoy more data than our predecessors would have believed possible:
measurements from satellites, in-situ sensors, or large-scale experiments; models of fluid
flow, structures, or biological systems. A spreadsheet is often inadequate to deal with such
large datasets. At the same time, the sciences and engineering have been the recipients of
an explosion in computational tools for calculations of all kinds. Whether we are looking
for a traditional statistical analysis routine or want to implement the latest machine learning
algorithm, someone else has written a tool we can use. The software engineering community
has also developed tools and legal frameworks that enable computational tools to be easily
shared and integrated into anyone’s programs. The result is that a person who knows how to
program can do more science and engineering.
A picture is worth a thousand words, so consider Figure 1.1: This is an image showing
the light received by the National Aeronautics and Space Administration (NASA) Kepler
Mission’s spacecraft (a space telescope designed to search for exoplanets) from the star
Kepler-10, around which orbits the first rocky exoplanet discovered by the spacecraft (Kepler-
10b).1 The Python code to read in the data via the Internet from the Mikulski Archive for
Space Telescopes (MAST), where the archived data resides, and create the plot is as follows:
That’s it! Three lines of code does it! This is why scientists and engineers need to learn to
program. We will not unpack these lines of code right now, but after going through the book,
we will have the tools to understand their meaning and use.
1 This example is slightly altered from the one given in the documentation of the lightkurve package (see Vinícius
et al. (2018)), a Python package used to access data from the Kepler Mission. That example is at http://lightkurve.
keplerscience.org/tutorials/2.02-recover-a-planet.html (accessed August 15, 2018). Information about the Kepler
Mission is at www.nasa.gov/mission_pages/kepler/overview/index.html (accessed August 20, 2018).
6 1 Prologue: Preparing to Program
(as humanly possible) that we will be able to use the language throughout our lives for
whatever scientific or engineering purpose – or business, artistic, literary, etc., purpose –
we wish.
although there is some scientific and engineering legacy code still written in Python 2.7.x, all major packages have
migrated to version 3.x.
1.3 Software We Will Need 7
To run the code in the sections listed above, please add these packages. Note the line-profiler
and memory-profiler packages are also referred to as line_profiler and memory_profiler, using
underscores instead of hyphens.
If any of the packages above are already installed, Anaconda Navigator will tell us when
we try to install it, so we do not have to worry about overwriting anything. If we do not know
whether we have all the packages we need, no worries. If while we are running a Python
program we receive a message such as:
ModuleNotFoundError: No module named 'netCDF4'
we can fix that by installing the package or module named, and then rerun our program.
That should be it for the preliminaries. We are ready now to begin our journey in learning
Python programming. We start with using Python to fulfill that basic computational need of
a scientist or engineer, the need to have a good calculator.
2 Python as a Basic Calculator
Pencil and paper are two of the greatest tools ever invented for studying science and
engineering problems. But, there comes a point when the amount of data and complexity of
the calculations require us to use more powerful approaches. The calculator is a scientist or
engineer’s basic workhorse for making those calculations. While Python has a wide range of
applications, from graphing to modeling to data analysis, the simplest (and sometimes most
useful) way is to use Python as a calculator. In fact, if our laptop is already open, it is often
easier to use Python to do simple (or not-so-simple) arithmetic rather than using a calculator.
In this chapter, we describe how to use Python as a basic calculator. The structure of this
chapter will be the same as that in most of the chapters. See the To the Student frontmatter
section for details. We center our discussion around examples of the task for the chapter and
the Python code to accomplish the task. Please do not expect the examples will make complete
sense when they are introduced. In the section after, we provide the explanation of what the
Python code is doing. Later in the chapter, we provide Try This! examples, chapter Self-Test
Questions, and a Chapter Summary.
Many basic calculators also include parentheses keys to enable grouping of operations. Some
can also store more than one value in the calculator’s memory for recall, or add a current
value to an existing value in memory.
Consider a cube whose sides are 2 in long. Here is a Python session to calculate the volume
of this cube:
>>> 2*2*2
8
8
2.1 Example of Python as a Basic Calculator 9
When the prompt for the Python interpreter appears (the interpreter is the place where
instructions in Python are entered in and the computer carries them out, i.e., executes them),
we type our arithmetic expression, press the Enter key (or Return key on some keyboards),
and the computer will execute our expression and print the result below. Starting the Python
interpreter is akin to turning on a calculator. Once the interpreter or calculator is turned on,
it is ready for us to enter numbers and do calculations. In the above example, the interpreter’s
prompt is the three greater-than symbols (>>>) and shows us where to start typing our
arithmetic expression. We do not type in the >>>; those symbols appear automatically when
the interpreter starts.
In addition to using the default Python interpreter, as shown above, we can also run an
interactive Python session in a different environment. An environment is the interface we use
to interact with the Python interpreter. Below is the same example as above but with the code
in a cell in the Jupyter notebook environment:
In [1]: 2*2*2
Out[1]: 8
We can group operations using parentheses. Here is an expression that calculates the
combined volume of two cubes, one with 2 in sides and another with 3 in sides:
>>> (2*2*2)+(3*3*3)
35
In [1]: (2*2*2)+(3*3*3)
Out[1]: 35
Finally, we can save the result of an expression by assigning it a name. Once saved, we
can use the saved values by referring to the name. We provide an example of calculating the
volume of two cubes, saving their values as variables, and using those variables in another
expression in Figure 2.1. In that example, the first three lines of code are each executed, one
at a time, in turn. The result is the output Python provides in the last line. The top part of the
figure shows how the code would be entered in and executed in the default Python interpreter.
In line 1 of the top part (which is equivalent to the first line of the In [1] cell of the bottom
part), we multiply three 2s and then save the result to the variable volume_cube_1. In line
2, we do the same for three 3s and save the result to the variable volume_cube_2. Finally, in
line 3, we add the contents of the variable volume_cube_1 and volume_cube_2 together,
and the Python interpreter prints the result, 35. The bottom part shows how the code would
be entered in and executed in a Jupyter notebook. Both top and bottom are equivalent, the
only difference being how the interface looks.
10 2 Python as a Basic Calculator
Out[1]: 35
The former are called binary operators whereas the latter are called unary operators. A little
confusingly, we also use the term “binary” when talking about how data are stored in a
computer. In those contexts, “binary” means a 0 or 1. This meaning of binary is described in
more detail in Section 9.2.2 and Chapter 18. Table 2.1 lists some basic arithmetic operators
Python uses (these are all binary operators). Later on in the text, we will encounter more
operators, both unary and binary.
When Python evaluates an arithmetic expression, it follows the standard mathematical
order of parenthetical blocks first, then exponentiation, then multiplication and division,
and finally addition and subtraction. Operations at the same level of priority are executed
left-to-right.1 In this example:
In [1]: 4+3*2
Out[1]: 10
In [2]: (4+3)*2
Out[2]: 14
we see that because multiplication has higher priority than addition, in cell In [1] the 3*2
is executed first before adding to the 4. In the In [2] expression, the parentheses force the
4+3 to be executed first before multiplying the result by 2.
The normal arithmetic operators listed in Table 2.1 act as expected. Division, however, is
a little more nuanced. The division (/) operator acts like regular division, which returns the
quotient and remainder in decimal form. Thus:
In [1]: 1/2
Out[1]: 0.5
1 See the Wikibooks page on Python operators for more details. We provide an up-to-date link to the page at
In [2]: 7/3
Out[2]: 2.3333333333333335
In [3]: 5/5
Out[3]: 1.0
In [4]: 5.0/5.0
Out[4]: 1.0
It does not matter whether the numerator or denominator is an integer or decimal number, the
result will be a decimal number. Also, in Out[2], it appears decimal numbers are not properly
represented in Python. We discuss this in more detail in Sections 8.2.7, 9.2.2, and 9.2.3. For
now, just note that decimal numbers are, in general, inexactly represented in computers.
Sometimes, however, we do not want division to give us the decimal result but instead only
want the quotient (as an integer) and discard the remainder by rounding down.2 In those
cases, we want to use integer division, which is given by the // operator:
In [1]: 1//2
Out[1]: 0
In [2]: 7//3
Out[2]: 2
In [3]: 5//5
Out[3]: 1
In [4]: 7//3.0
Out[4]: 2.0
In [5]: -9/2
Out[5]: -4.5
In [6]: -9//2
Out[6]: -5
If either of the operands (the values to the left and right of the // operator) is a decimal
number, integer division is still done, but the result is a decimal number.
Teaser trailer: In this section, we have been discussing integers and decimals as if they are
different entities in Python, whereas in mathematics 2 and 2.0 are identical. This is a hint
of the programming concept called typing, where we define different kinds of values to have
different properties. We address that topic in Section 5.2.7.
2.2.2 Variables
On a calculator, we often save values in memory to use later. In Python, we save values by
setting them to variable names. We can then use the values by name. In line 2 of the top part
of Figure 2.1, we take the result of the expression 2*2*2 and give it a name. In doing so, if
later on in our Python calculator session we make reference to that name, it is the same as
referring to the result of the expression (in this case the value 8). We do something similar
in line 3 for the volume of the second cube. The act of giving a name to a value is called
assigning a variable.
In Python, we use an equal sign to do the assignment. The name of the variable goes to
the left of the equal sign and the expression whose result we are assigning that variable to is
to the right of the equal sign. Thus, in line 2 of the top part of Figure 2.1, the variable name
is volume_cube_1 and the value we assign volume_cube_1 to is 8, which is the result of
the expression 2*2*2. These tasks in line 2 happen in this order: First, the expression 2*2*2
is evaluated to obtain 8; then, the variable volume_cube_1 is attached to that 8.
The order of these tasks is important. In most everyday life, the equal sign connotes
mathematical equality or “interchangeability” or “sameness.” That is not what is happening
in assignment. Here is an example of why this difference is important. Consider this line of
Python code:
If the above line of code were a mathematical equation, it would make no sense. We
could subtract the variable volume_cube_1 from both sides and obtain the mathematical
equation:
0 = 100
which is false. Thus, what is happening in the earlier line of code is not a mathematical expres-
sion. Instead, what is happening is that the right-hand-side expression volume_cube_1
+ 100 is first evaluated using whatever the current value of volume_cube_1 is. So, if
volume_cube_1 were equal to 8, the right-hand-side expression evaluates to 108. Then, the
variable volume_cube_1 is set to that value, overwriting the old value of volume_cube_1.
At the end of executing the above line of code, volume_cube_1 would be set to 108, a value
100 larger than volume_cube_1 held before the line of code was executed.
14 2 Python as a Basic Calculator
Variables in Python differ from variables in mathematics in another way. When we have a
mathematical equation such as:
y = mx + b
it does not matter whether we have values defined for any of the variables. With the equation
written as-is, we can manipulate the terms using the rules of algebra, for instance rewriting
the equation as:
y−b
x=
m
Variables in Python, however, do not exist until we create them through assignment. Thus,
this line of code would not work:
y = (m * x) + b
unless m, x, and b were previously defined. In contrast, while the single line of code above
would not work, this set of lines would:
In [1]: m = 0.5
x = 2.1
b = -13.0
y = (m * x) + b
The m, x, and b variables do not have to be assigned to a value immediately before y is assigned,
but they have to be assigned somewhere before y is assigned.
We call a variable that “grows,” as in this line of code:
we call the variable a deaccumulator. Because the same variable can gain or lose value over
multiple lines of code, sometimes it is easier to just call a variable whose value we change in
this way an accumulator. Note that an accumulator or deaccumulator variable is still a regular
variable. But, because we use the variable in such a way that it gains or loses value, we give it
a special name to highlight that use.
Consider again Figure 2.1. Let us say we changed the code a little, to the following:
Out[1]: 35
2.2 Python Programming Essentials 15
In [1]: a = 2
a
Out[1]: 2
This method only works for one variable in the cell, the variable we last type in the cell. If we
want to see the contents of more than one variable, we will need to use the print command.
That command is introduced in Try This! 2-4 and further discussed in Section 3.2.4.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebooknice.com