100% found this document useful (6 votes)
28 views

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

The document provides information about the ebook 'An Introduction to Python Programming for Scientists and Engineers', which is designed to teach Python programming through examples relevant to various scientific disciplines. It emphasizes practical applications, active learning, and includes exercises to reinforce concepts. The authors are experienced educators and professionals in their fields, aiming to make Python accessible for beginners in science and engineering.

Uploaded by

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

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

The document provides information about the ebook 'An Introduction to Python Programming for Scientists and Engineers', which is designed to teach Python programming through examples relevant to various scientific disciplines. It emphasizes practical applications, active learning, and includes exercises to reinforce concepts. The authors are experienced educators and professionals in their fields, aiming to make Python accessible for beginners in science and engineering.

Uploaded by

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

Download the Full Ebook and Access More Features - ebooknice.

com

(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
https://ebooknice.com/product/an-introduction-to-python-
programming-for-scientists-and-engineers-48950520

OR CLICK HERE

DOWLOAD EBOOK

Download more ebook instantly today at https://ebooknice.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason;


Viles, James ISBN 9781459699816, 9781743365571,
9781925268492, 1459699815, 1743365578, 1925268497
https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

ebooknice.com

(Ebook) Matematik 5000+ Kurs 2c Lärobok by Lena


Alfredsson, Hans Heikne, Sanna Bodemyr ISBN 9789127456600,
9127456609
https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312

ebooknice.com

(Ebook) SAT II Success MATH 1C and 2C 2002 (Peterson's SAT


II Success) by Peterson's ISBN 9780768906677, 0768906679

https://ebooknice.com/product/sat-ii-success-
math-1c-and-2c-2002-peterson-s-sat-ii-success-1722018

ebooknice.com

(Ebook) Master SAT II Math 1c and 2c 4th ed (Arco Master


the SAT Subject Test: Math Levels 1 & 2) by Arco ISBN
9780768923049, 0768923042
https://ebooknice.com/product/master-sat-ii-math-1c-and-2c-4th-ed-
arco-master-the-sat-subject-test-math-levels-1-2-2326094

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

(Ebook) Introduction to Python for Engineers and


Scientists: Open Source Solutions for Numerical
Computation by Sandeep Nagar ISBN 9781484232033,
1484232038
https://ebooknice.com/product/introduction-to-python-for-engineers-
and-scientists-open-source-solutions-for-numerical-
computation-51197000
ebooknice.com

(Ebook) Prototyping Python Dashboards for Scientists and


Engineers by --

https://ebooknice.com/product/prototyping-python-dashboards-for-
scientists-and-engineers-55888336

ebooknice.com

(Ebook) Monte-Carlo Simulation: An Introduction for


Engineers and Scientists by Alan Stevens ISBN
9781032280776, 1032280778
https://ebooknice.com/product/monte-carlo-simulation-an-introduction-
for-engineers-and-scientists-44187934

ebooknice.com

(Ebook) Fiber Optic Sensors: An Introduction for Engineers


and Scientists by Eric Udd ISBN 9780470068106, 0470068108

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.

Johnny Wei-Bing Lin is an Associate Teaching Professor and Director of Undergraduate


Computing Education in the Division of Computing and Software Systems at the University
of Washington Bothell, and an Affiliate Professor of Physics and Engineering at North Park
University. He was the founding Chair of the American Meteorological Society’s annual
Python Symposium.

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.

Kim Gunnerson recently retired as an Associate Teaching Professor at the University of


Washington Bothell, where she taught chemistry and introductory computer programming.

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

Johnny Wei-Bing Lin


University of Washington Bothell and North Park University

Hannah Aizenman
City College of New York

Erin Manette Cartas Espinel


Envestnet Tamarac

Kim Gunnerson
University of Washington Bothell

Joanne Liu
Novozymes A/S
University Printing House, Cambridge CB2 8BS, United Kingdom

One Liberty Plaza, 20th Floor, New York, NY 10006, USA

477 Williamstown Road, Port Melbourne, VIC 3207, Australia

314-321, 3rd Floor, Plot 3, Splendor Forum, Jasola District Centre,


New Delhi – 110025, India

103 Penang Road, #05–06/07, Visioncrest Commercial, Singapore 238467

Cambridge University Press is part of the University of Cambridge.

It furthers the University’s mission by disseminating knowledge in the pursuit of


education, learning, and research at the highest international levels of excellence.

www.cambridge.org
Information on this title: www.cambridge.org/highereducation/isbn/9781108701129
DOI: 10.1017/9781108571531

© Johnny Wei-Bing Lin, Hannah Aizenman, Erin Manette Cartas Espinel,


Kim Gunnerson, and Joanne Liu 2022

This publication is in copyright. Subject to statutory exception


and to the provisions of relevant collective licensing agreements,
no reproduction of any part may take place without the written
permission of Cambridge University Press.
First published 2022

Printed in the United Kingdom by TJ Books Limited, Padstow Cornwall

A catalogue record for this publication is available from the British Library.

Library of Congress Cataloging-in-Publication Data


Names: Lin, Johnny Wei-Bing, 1972– author. | Aizenman, Hannah, 1987– author. |
Espinel, Erin Manette Cartas, 1965– author. | Gunnerson, Kim Noreen, 1965– author. |
Liu, Joanne (Joanne K.), author.
Title: An introduction to Python programming for scientists and engineers /
Johnny Wei-Bing Lin, University of Washington, Bothell, Hannah Aizenman,
City College of New York, Erin Manette Cartas Espinel, Envestnet Tamarac,
Kim Gunnerson, University of Washington, Bothell, Joanne Liu, Biota Technology Inc.
Description: First edition. | Cambridge, United Kingdom ; New York, NY :
Cambridge University Press, 2022. | Includes bibliographical references and index.
Identifiers: LCCN 2022000136 | ISBN 9781108701129 (paperback)
Subjects: LCSH: Python (Computer program language) | Computer programming. |
Engneering–Data processing. | BISAC: SCIENCE / Earth Sciences / General
Classification: LCC QA76.73.P98 L55 2022 | DDC 005.13/3–dc23/eng/20220304
LC record available at https://lccn.loc.gov/2022000136

ISBN 978-1-108-70112-9 Paperback

Cambridge University Press has no responsibility for the persistence or accuracy


of URLs for external or third-party internet websites referred to in this publication
and does not guarantee that any content on such websites is, or will remain,
accurate or appropriate.
Contents

Detailed Contents page vii


Preface xvii
To the Student xxiii
Notices and Disclaimers xxvi
Acknowledgments xxix

Part I Getting Basic Tasks Done 1


1 Prologue: Preparing to Program 3

2 Python as a Basic Calculator 8

3 Python as a Scientific Calculator 27

4 Basic Line and Scatter Plots 52

5 Customized Line and Scatter Plots 88

6 Basic Diagnostic Data Analysis 124

7 Two-Dimensional Diagnostic Data Analysis 176

8 Basic Prognostic Modeling 209

9 Reading In and Writing Out Text Data 261

10 Managing Files, Directories, and Programs 327

Part II Doing More Complex Tasks 353

11 Segue: How to Write Programs 355

12 n-Dimensional Diagnostic Data Analysis 365

13 Basic Image Processing 394

v
vi Contents

14 Contour Plots and Animation 439

15 Handling Missing Data 483

Part III Advanced Programming Concepts 503


16 More Data and Execution Structures 505

17 Classes and Inheritance 536

18 More Ways of Storing Information in Files 570

19 Basic Searching and Sorting 595

20 Recursion 633

Part IV Going from a Program Working to Working Well 655


21 Make It Usable to Others: Documentation and Sphinx 657

22 Make It Fast: Performance 666

23 Make It Correct: Linting and Unit Testing 683

24 Make It Manageable: Version Control and Build Management 693

25 Make It Talk to Other Languages 702

Appendix A List of Units 706

Appendix B Summary of Data Structures 708

Appendix C Contents by Programming Topic 709

Glossary 719
Acronyms and Abbreviations 726
Bibliography 727
Index 729
Detailed Contents

Preface page xvii


To the Student xxiii
Notices and Disclaimers xxvi
Acknowledgments xxix

Part I Getting Basic Tasks Done 1


1 Prologue: Preparing to Program 3
1.1 What Is a Program and Why Learn to Program? 3
1.2 What Is Python and Why Learn This Language? 5
1.3 Software We Will Need 6

2 Python as a Basic Calculator 8


2.1 Example of Python as a Basic Calculator 8
2.2 Python Programming Essentials 10
2.2.1 Expressions and Operators 10
2.2.2 Variables 13
2.2.3 The Python Interpreter 15
2.3 Try This! 18
2.4 More Discipline-Specific Practice 24
2.5 Chapter Review 24
2.5.1 Self-Test Questions 24
2.5.2 Chapter Summary 25
2.5.3 Self-Test Answers 26

3 Python as a Scientific Calculator 27


3.1 Example of Python as a Scientific Calculator 27
3.2 Python Programming Essentials 28
3.2.1 Using Prewritten Functions 29
3.2.2 Importing Modules and Using Module Items 30
3.2.3 Writing and Using Our Own Functions 32
3.2.4 A Programmable Calculator 35
3.2.5 Python Interpreter and Code-Writing Environments for
More Complex Programs 38
3.3 Try This! 41

vii
viii Detailed Contents

3.4 More Discipline-Specific Practice 47


3.5 Chapter Review 47
3.5.1 Self-Test Questions 47
3.5.2 Chapter Summary 48
3.5.3 Self-Test Answers 49

4 Basic Line and Scatter Plots 52


4.1 Example of Making Basic Line and Scatter Plots 52
4.2 Python Programming Essentials 54
4.2.1 Positional Input Parameters for Required Input 55
4.2.2 Introduction to Lists and Tuples 58
4.2.3 Introduction to Strings 62
4.2.4 Introduction to Commenting and Jupyter Markdown 66
4.3 Try This! 69
4.4 More Discipline-Specific Practice 81
4.5 Chapter Review 81
4.5.1 Self-Test Questions 81
4.5.2 Chapter Summary 83
4.5.3 Self-Test Answers 85

5 Customized Line and Scatter Plots 88


5.1 Example of Customizing Line Plots 88
5.2 Python Programming Essentials 91
5.2.1 Optional Input into Functions Using Keyword Input Parameters 91
5.2.2 Customizing How the Plot Looks 93
5.2.3 Handling Multiple Figures or Curves 96
5.2.4 Adjusting the Plot Size 97
5.2.5 Saving Figures to a File 98
5.2.6 Introduction to Array Calculations 99
5.2.7 The Concept of Typing 103
5.3 Try This! 106
5.4 More Discipline-Specific Practice 117
5.5 Chapter Review 117
5.5.1 Self-Test Questions 117
5.5.2 Chapter Summary 119
5.5.3 Self-Test Answers 121

6 Basic Diagnostic Data Analysis 124


6.1 Example of Basic Diagnostic Data Analysis 124
6.2 Python Programming Essentials 126
6.2.1 More on Creating Arrays and Inquiring about Arrays 128
6.2.2 More on Functions on Arrays 132
Detailed Contents ix

6.2.3 Going Through Array Elements and an Introduction to Loops 134


6.2.4 Introduction to Asking Questions of Data and Branching 139
6.2.5 Examples of One-Dimensional Loops and Branching 148
6.2.6 Docstrings 153
6.2.7 Three Tips on Writing Code 155
6.3 Try This! 158
6.4 More Discipline-Specific Practice 170
6.5 Chapter Review 170
6.5.1 Self-Test Questions 170
6.5.2 Chapter Summary 171
6.5.3 Self-Test Answers 173

7 Two-Dimensional Diagnostic Data Analysis 176


7.1 Example of Two-Dimensional Diagnostic Data Analysis 176
7.2 Python Programming Essentials 182
7.2.1 The Shape of Two-Dimensional Arrays 183
7.2.2 Creating Two-Dimensional Arrays 184
7.2.3 Accessing, Setting, and Slicing in a Two-Dimensional Array 186
7.2.4 Array Syntax and Functions in Two-Dimensional Arrays 190
7.2.5 Nested for Loops 191
7.3 Try This! 194
7.4 More Discipline-Specific Practice 203
7.5 Chapter Review 203
7.5.1 Self-Test Questions 203
7.5.2 Chapter Summary 205
7.5.3 Self-Test Answers 207

8 Basic Prognostic Modeling 209


8.1 Example of a Basic Prognostic Model 209
8.2 Python Programming Essentials 217
8.2.1 Random Numbers in Computers 217
8.2.2 Scalar Boolean Type and Expressions 221
8.2.3 Nested Branching 230
8.2.4 Looping an Indefinite Number of Times Using while 232
8.2.5 Making Multiple Subplots 236
8.2.6 More on Nested Loops 237
8.2.7 Conditionals Using Floating-Point Numbers 239
8.3 Try This! 241
8.4 More Discipline-Specific Practice 252
8.5 Chapter Review 252
8.5.1 Self-Test Questions 252
8.5.2 Chapter Summary 254
8.5.3 Self-Test Answers 257
x Detailed Contents

9 Reading In and Writing Out Text Data 261


9.1 Example of Reading In and Writing Out Text Data 262
9.2 Python Programming Essentials 267
9.2.1 Introduction to Objects 268
9.2.2 Arrays as Objects 269
9.2.3 Lists as Objects 277
9.2.4 Strings as Objects 280
9.2.5 Copying Variables, Data, and Objects 286
9.2.6 Reading and Writing Files 290
9.2.7 Catching File Opening and Other Errors 298
9.3 Try This! 300
9.4 More Discipline-Specific Practice 317
9.5 Chapter Review 317
9.5.1 Self-Test Questions 317
9.5.2 Chapter Summary 319
9.5.3 Self-Test Answers 321

10 Managing Files, Directories, and Programs 327


10.1 Example of Managing Files, Directories, and Programs 328
10.2 Python Programming Essentials 331
10.2.1 Filenames, Paths, and the Working Directory 332
10.2.2 Making and Removing Empty Directories 335
10.2.3 Moving and Renaming Files and Directories 337
10.2.4 Copying and Deleting Files and Directories 338
10.2.5 Listing the Contents of a Directory 340
10.2.6 Testing to See What Kind of “File” Something Is 341
10.2.7 Running Non-Python Programs in Python 342
10.3 Try This! 343
10.4 More Discipline-Specific Practice 347
10.5 Chapter Review 347
10.5.1 Self-Test Questions 347
10.5.2 Chapter Summary 348
10.5.3 Self-Test Answers 350

Part II Doing More Complex Tasks 353


11 Segue: How to Write Programs 355
11.1 From Blank Screen to Program: A Process to Follow 355
11.2 The Importance of Testing 360
11.3 The Importance of Style Conventions 363
Detailed Contents xi

12 n-Dimensional Diagnostic Data Analysis 365


12.1 Example of n-Dimensional Diagnostic Data Analysis 365
12.2 Python Programming Essentials 367
12.2.1 The Shape of and Indexing n-Dimensional Arrays 368
12.2.2 Selecting Subarrays from n-Dimensional Arrays 370
12.2.3 Array Syntax and Functions in n-Dimensional Arrays 372
12.2.4 Reshaping n-Dimensional Arrays and Memory Locations of Array
Elements 374
12.2.5 Subarrays and Index Offset Operations 376
12.2.6 Triple Nested Loops and Mixing Array Syntax/Selection and Looping 378
12.2.7 Summary Table of Some Array Functions 380
12.3 Try This! 382
12.4 More Discipline-Specific Practice 386
12.5 Chapter Review 387
12.5.1 Self-Test Questions 387
12.5.2 Chapter Summary 389
12.5.3 Self-Test Answers 391

13 Basic Image Processing 394


13.1 Example of Image Processing 394
13.2 Python Programming Essentials 400
13.2.1 Reading, Displaying, and Writing Images in Matplotlib 401
13.2.2 Boolean Arrays 404
13.2.3 Array Syntax and Functions and Asking Questions of Data in Arrays 408
13.2.4 Performance of Looping and Array Syntax and Functions 414
13.2.5 The NumPy reduce Method 416
13.2.6 Looping Through Lists of Objects 417
13.3 Try This! 419
13.4 More Discipline-Specific Practice 430
13.5 Chapter Review 431
13.5.1 Self-Test Questions 431
13.5.2 Chapter Summary 432
13.5.3 Self-Test Answers 434

14 Contour Plots and Animation 439


14.1 Example of Making Contour Plots and Animations 440
14.2 Python Programming Essentials 445
14.2.1 An Introduction to Matplotlib’s Object API 446
14.2.2 Line and Shaded Contour Plots 451
14.2.3 Using cartopy to Overlay Maps 453
14.2.4 Basic Animation Using Matplotlib 456
14.2.5 Flexible Functions and Dictionaries 459
xii Detailed Contents

14.3 Try This! 465


14.4 More Discipline-Specific Practice 477
14.5 Chapter Review 477
14.5.1 Self-Test Questions 477
14.5.2 Chapter Summary 479
14.5.3 Self-Test Answers 481

15 Handling Missing Data 483


15.1 Example of Handling Missing Data 483
15.2 Python Programming Essentials 487
15.2.1 Approach 1: Define a Data Value as Missing and Process
with Boolean Arrays or Expressions 488
15.2.2 Approach 2: Use Series and IEEE NaN Values 490
15.2.3 Approach 3: Use Masked Arrays 492
15.2.4 Which Approach Is Better? 493
15.3 Try This! 494
15.4 More Discipline-Specific Practice 498
15.5 Chapter Review 498
15.5.1 Self-Test Questions 498
15.5.2 Chapter Summary 499
15.5.3 Self-Test Answers 501

Part III Advanced Programming Concepts 503


16 More Data and Execution Structures 505
16.1 Example of Using More Advanced Data and Execution Structures 505
16.1.1 Solution 1: Explicitly Call Functions and Store Results in Variables 506
16.1.2 Solution 2: Explicitly Call Functions and Store Results in Arrays 507
16.1.3 Solution 3: Explicitly Call Functions and Store Results in Dictionaries 508
16.1.4 Solution 4: Store Results and Functions in Dictionaries 509
16.2 Python Programming Essentials 511
16.2.1 More Data Structures 511
16.2.2 More Execution Structures 519
16.2.3 When to Use Different Data and Execution Structures 521
16.3 Try This! 523
16.4 More Discipline-Specific Practice 529
16.5 Chapter Review 530
16.5.1 Self-Test Questions 530
16.5.2 Chapter Summary 531
16.5.3 Self-Test Answers 533
Detailed Contents xiii

17 Classes and Inheritance 536


17.1 Examples of Classes and Inheritance 536
17.1.1 Scientific Modeling Example 537
17.1.2 Scientific Bibliography Example 544
17.2 Python Programming Essentials 546
17.2.1 Defining and Using a Class 546
17.2.2 Inheritance 550
17.2.3 More Sophisticated Sorting Using sorted 553
17.2.4 Why Create Our Own Classes? 554
17.2.5 Automating Handling of Objects and Modules 557
17.3 Try This! 560
17.4 More Discipline-Specific Practice 564
17.5 Chapter Review 564
17.5.1 Self-Test Questions 564
17.5.2 Chapter Summary 566
17.5.3 Self-Test Answers 568

18 More Ways of Storing Information in Files 570


18.1 Examples of Using Other File Formats 570
18.2 Python Programming Essentials 576
18.2.1 Excel Files 576
18.2.2 pickle Files 578
18.2.3 netCDF files 579
18.3 Try This! 583
18.4 More Discipline-Specific Practice 589
18.5 Chapter Review 589
18.5.1 Self-Test Questions 589
18.5.2 Chapter Summary 590
18.5.3 Self-Test Answers 592

19 Basic Searching and Sorting 595


19.1 Examples of Searching and Sorting 595
19.2 Python Programming Essentials 598
19.2.1 Summary of Some Ways to Search and Sort 598
19.2.2 Searching and Sorting Algorithms 601
19.2.3 Basic Searching and Sorting Using pandas 611
19.3 Try This! 622
19.4 More Discipline-Specific Practice 628
19.5 Chapter Review 628
19.5.1 Self-Test Questions 628
19.5.2 Chapter Summary 629
19.5.3 Self-Test Answers 631
xiv 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

Part IV Going from a Program Working to Working Well 655


21 Make It Usable to Others: Documentation and Sphinx 657
21.1 Introduction 657
21.2 Principles of Documenting 657
21.3 General Convention for Docstrings: The NumPy Format 659
21.4 The Sphinx Documentation Generator 660

22 Make It Fast: Performance 666


22.1 Introduction 666
22.2 Preliminaries 666
22.2.1 Describing the Complexity of Code 666
22.2.2 Practices That Can Result in Inefficient Code 668
22.3 Finding the Bottlenecks Using Profilers 670
22.3.1 timeit 671
22.3.2 cProfile 672
22.3.3 line-profiler 674
22.3.4 memory-profiler 676
22.4 Fixing the Bottlenecks 678
22.4.1 Generators 678
22.4.2 Just-in-Time Compilation 680
22.5 Pitfalls When Trying to Improve Performance 682

23 Make It Correct: Linting and Unit Testing 683


23.1 Introduction 683
23.2 Linting 683
23.3 Unit Testing 686
23.3.1 unittest 687
23.3.2 pytest 688
23.4 The “Test-Driven Development” Process 690
Detailed Contents xv

24 Make It Manageable: Version Control and Build Management 693


24.1 Introduction 693
24.2 Version Control 693
24.2.1 Using Git as a Single User 694
24.2.2 Using Git as a User Who Is Part of a Collaboration 696
24.2.3 Using Git with Branching 697
24.3 Packaging 698
24.4 Build Management and Continuous Integration 699

25 Make It Talk to Other Languages 702


25.1 Introduction 702
25.2 Talking with Fortran Programs 702
25.3 Talking with C/C++ Programs 704

Appendix A List of Units 706

Appendix B Summary of Data Structures 708

Appendix C Contents by Programming Topic 709


C.1 Introductory Programming Topics 709
C.1.1 What Is a Program and General Elements of Python 709
C.1.2 Variables and Expressions 710
C.1.3 Typing and Some Basic Types 710
C.1.4 Strings 711
C.1.5 Functions 711
C.1.6 Branching, Conditionals, and Booleans 712
C.1.7 Looping 712
C.1.8 Console Input and Output 713
C.1.9 Text File Input and Output 713
C.1.10 Exceptions 713
C.1.11 Arrays 714
C.1.12 Classes 715
C.2 Intermediate Programming Topics 715
C.2.1 Abstract Data Types and Structures 715
C.2.2 Algorithm Analysis 716
C.2.3 Searching and Sorting 716
C.2.4 Recursion 717
C.3 Other Topics 717
C.3.1 How to Program and Programming Style 717
C.3.2 Distributions and Interactive Development Environments (IDEs) 717
xvi Detailed Contents

C.3.3 Packages and Modules 717


C.3.4 Calculation Functions and Modules 718
C.3.5 Visualization 718

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

Structure of the Textbook


The textbook is divided into four parts. Parts I–III, collectively, cover most of the topics of
a CS1 and CS2 sequence:
• Part I shows how to get the basic scientific and engineering workflow tasks done, including
visualization, modeling, analysis, input/output, and computer administration.
• Part II shows us how to do more advanced tasks, building off of what we have seen in
Part I. Throughout, the programming is taught through learning how to do the science
and engineering workflow tasks, so almost every chapter in Parts I–II addresses a different
science or engineering task we can use Python programming for.
• The chapters in Part III, because they cover more advanced programming concepts that are
better discussed in computer science terms, are organized more traditionally, with chapters
on more advanced data structures, classes and inheritance, basic searching and sorting,
and recursion. Nonetheless, even in Part III, we connect those concepts to science and
engineering workflow tasks.
Typical CS2 topics the textbook does not cover include linked lists, divide-and-conquer
sorting algorithms, and trees.
Part IV goes beyond the topics of a sequence of introductory programming or scientific
computing courses to describe how to turn our programs into something really robust.

Structure of the Chapters


The text takes a very uniform approach to each of the chapters in Parts I–III, as follows:
• The first section describes the task and gives some examples of using Python to accomplish
that task. These examples and problems are general enough to be understood by most
scientists and engineers.
• The second section describes why the example in the first section works the way it does: the
programming concepts and Python syntax are described and demonstrated in this section.
• The third section provides exercises/examples, often similar to the examples in the first
section, for the reader to try, along with solutions and discussion of why the solution works.
Additional programming and Python concepts are often discussed in these solutions.
• The fourth section briefly describes the online exercises and problems that are discipline-
specific (physics, chemistry, and biology), for further explication and practice.
• The final section is a chapter review containing self-test questions (with answers at the end
of the section) and a chapter summary.
Chapters 1 and 11 are the exceptions in Parts I–III, having a different organization and lacking
the exercises, questions, and chapter review as described above.
Because the chapters in Part IV cover techniques, packages, and utilities (some of which
are still evolving) that do not lend themselves to a simple scientific or engineering workflow
Preface xix

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:

Part IV: Going from


a Program Working
to Working Well

Part III: Advanced


Programming Concepts More
Concise
Part II: Doing More Complex
Tasks

Part I: Getting Basic Tasks Done

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.

The Logic Behind Some Decisions on Topic Coverage and Sequence


Some of the decisions about coverage and sequence may be surprising, so the rationale is
explained here:
• By basing the structure of most of the chapters in Parts I–II on science and engineering
workflow tasks, syntax is addressed in pieces. That is, there is no single chapter on variables,
single chapter on branching, etc. Rather, those topics are covered over several chapters, in
a kind of spiral approach. Pedagogically, this is better because it allows us to learn things
a little at a time with subsequent treatments of a topic reinforcing what we learned earlier.
Learning in this way is treated as a spiral rather than as a line. But, there are at least two
costs with this method of learning. First, the first time we see a particular structure in
xx Preface

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.

Topic Sequence and Flexible Approach for Different Course Lengths


• Part I is material for approximately one quarter-long (10 week) class. The material works
well for an introductory programming course where the students have no prior experience
with programming.
Preface xxi

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

Typesetting and Coloring Conventions


Throughout the textbook, we use different forms of typesetting and coloring to provide
additional clarity and functionality. Some of the special typesetting conventions we use
include:
• Inline source code. These are instructions interspersed in the paragraphs of the textbook
that tell Python what to do. They are typeset in a dark red, monospace font, as in a = 4.
• Inline commands to type on your keyboard or printed to the screen. Typeset in a dark red,
monospace font, as in print('hello').
• Inline generic arguments or values. These labels are placeholders to be replaced by snippets
of code or concrete values. These are typeset in a dark red, italicized, proportional font, in
between a less than sign and a greater than sign, as in <condition>.
• Blocks or listing items of source code, commands, generic arguments, or values. These are
typeset in an indented block quotation structure or listing structure in a black font.
• File contents (that are not source code). These are typeset in an indented block quotation
structure in a black, monospace font.
• File, directory, and app names. Typeset in a black, italicized, proportional font, as in
/usr/bin.
• Key terms. On first use, these are typeset in a dark blue, bold, proportional font, as in
program, and can be found in the Glossary.
General references to application, library, module, and package names are typeset the same
as regular text. Thus, references to the Matplotlib package are typeset just as in this sentence.
As most packages have unique names, this should not be confusing. In the few cases where
the package names are regular English words (e.g., the time module), references to the module
will hopefully be clear from the context.

Assessment and Practice for Students


This text and the online Jupyter notebooks provide an abundance of opportunities for
students to practice what they are learning:
xxii Preface

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

Supporting Resources and Updates to This Textbook


The textbook’s website, www.cambridge.org/core/resources/pythonforscientists, contains
updates to and supporting resources for the textbook. This includes:
• Web pages describing some topics in more detail.
• Jupyter notebooks with exercises and problems.
• Copies of the larger datasets and images referenced in this textbook.
• A list of addenda and errata.
• Links to key external sites.

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.

Applications and Exercises


The textbook provides the following kinds of questions and problems in Parts I–III:
• Try This!. These are exercises/worked examples and are found in the print/digital book.
They are similar in complexity to the main chapter examples and contain solutions and
discussion of the solution. The Try This! sections also extend the discussion earlier in the
chapters, introducing new concepts.
• Chapter Review Self-Test Questions. These are found in the print/digital book. These are
relatively short questions that give you a first-cut assessment of your understanding of the
material in the chapter. The answers to these questions are found at the end of the chapter.
• Discipline-Specific Try This!. These are found online. They are similar to the exercises
discussed in the print/digital book in the Try This! sections. We give you a Jupyter notebook
with the Discipline-Specific Try This! and then another Jupyter notebook with answers to
the Try This!.
• Discipline-Specific Homework Problems. These are found online. They are designed to be
assigned by instructors for homework. We give you a blank Jupyter notebook with the
Problems. These Problems are generally more involved than the Discipline-Specific Try
This!.
All Discipline-Specific exercises and problems are in the form of Jupyter notebooks that
can be downloaded to your own computer and run locally. The Discipline-Specific Jupyter
notebooks are at www.cambridge.org/core/resources/pythonforscientists/jupyter-notebooks/.
Currently, notebooks for biology, chemistry, and physics are provided. We hope to include
notebooks for other disciplines in the future. Details on using Jupyter notebooks begin in
Section 2.2.3.

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.

Using the Textbook


We recommend that you approach the chapters in the following manner.
First, read the main chapter example. If possible, type in the code for the example and
see what you get. This is more doable for earlier chapters, where the code is shorter. In later
chapters, the benefits of typing in the code are probably not worth the time to key it all in. As
you read the main chapter example, you might not understand everything in the example. If
so, that is okay. The purpose of the main chapter example is not to teach you the concepts in
the chapter. That is what the rest of the chapter is for. The main chapter example is there to
give you a sense of how we can use Python to solve a particular science or engineering task
and to motivate the rest of the chapter’s discussion and exercises.
Second, read the Python Programming Essentials section. In most chapters, this section
will have small examples you can type in. Please do so. This will help your learning.
Third, do the Try This!. Do not read read the solution that immediately follows until you
have done the Try This!. If you just read the Try This! and skip immediately to the solution,
you will circumvent the learning process. Doing and working problems really help us learn!
Also, remember the discussion of these exercises contains additional material regarding the
chapter’s topics. Do not skip the Try This! as if they are optional, “mere examples.”
Fourth, do as many of the Discipline-Specific Try This! you have the time to do. After
you do them, look at their solutions and see if you can explain the reason for any differences
between your solution and the solution notebook.
Fifth, to increase the sophistication of your understanding of the topics involved, do at
least a few of the Discipline-Specific Homework Problems. The solutions are only available
to instructors, but the practice itself will help with your learning.
The Chapter Review Self-Test Questions can be used to test your understanding of the
material. You might want to use them for studying for exams, but you do not need to wait
for an exam to go through them. As you are reading the textbook, these questions might also
help give you a sense of your comprehension. Note, though, that these questions are not very
difficult, so you should not conclude that if you are able to answer all the questions easily that
you will do fine on an exam.
The Chapter Summary provides one additional opportunity for you to see the topics again.
It should not be used as a substitute for taking your own notes or creating your own study
sheet for an exam.
One final piece of advice. Wherever we suggest you read the text, we are implicitly assuming
you will read slowly. Really, really slowly. When we read code, we have to go line-by-line and
term-by-term. We have to ask what the state of the variables are before that line, what the
state of the variables are after that line, and what did the line do to cause (or not cause) any
To the Student xxv

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

Mark and Trademark Acknowledgments


Anaconda, Anaconda Navigator, Conda, and Numba are marks and/or registered trade-
marks of Anaconda, Inc. Apple, Mac, Mac OS, and OS X are registered trademarks of Apple
Inc. Azure, Excel, Microsoft, PowerShell, Windows, and Word are registered trademarks of
Microsoft Corporation in the United States and/or other countries. ChromeTM browser is a
trademark of Google LLC. Debian is a registered trademark of Software in the Public Inter-
est, Inc. Django is a trademark of the Django Software Foundation. Git is either a registered
trademark or trademark of Software Freedom Conservancy, Inc., corporate home of the Git
Project, in the United States and/or other countries. GITHUB® is an exclusive trademark
registered in the United States by GitHub, Inc. GitLab is a registered trademark of GitLab,
Inc. GNOME® is a trademark of the GNOME Foundation. GNU is an operating system
supported by the Free Software Foundation. Jupyter®, JupyterHub, and derivative word
marks are trademarks or registered trademarks of NumFOCUS. Kubernetes® is a registered
trademark in the United States and/or other countries of The Linux Foundation. LibreOffice
is a registered trademark of The Document Foundation. Linux is a trademark owned by
Linus Torvalds. Matlab and MathWorks are registered trademarks of The MathWorks, Inc.
PyCharm1 is a trademark of JetBrains s.r.o. Python is a registered trademark of the Python
Software Foundation. Stack Overflow is a trademark of Stack Exchange Inc. Ubuntu is a
registered trademark of Canonical Ltd. All other trademarks and marks mentioned in this
book are the property of their respective owners. Any errors or omissions in trademark and/or
other mark attributions are not meant to be assertions or denials of trademark and/or other
mark rights.

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

Attribution 4.0 International Public License is available at https://creativecommons.org/


licenses/by/4.0/legalcode. The images in the present work have been modified from their
original form in Volkman et al.
The screen shots in Figures 2.3, 3.7, 3.8, 3.9, 21.2, 21.3, and 21.4 are reprinted with
permission from Apple Inc.
The code in Figure 24.1 is © 2010–2021, Holger Krekel and others. The code is used by
permission under the conditions of the MIT License. The license agreement is available at
https://github.com/tox-dev/tox/blob/master/LICENSE.2
Code portions and ideas referenced throughout the text are footnoted or otherwise
referenced in the text. The code portions and ideas in Chapter 14, however, are built off
of longer blocks of code as well as a larger variety of code sources, most prominently
the cartopy manual (Met Office, 2010–2015), licensed under an Open Government License
(www.nationalarchives.gov.uk/doc/open-government-licence/version/2/), and the Matplotlib
documentation (matplotlib.org/contents.html; also see Hunter (2007)). Traditional footnot-
ing and referencing does not work as well for this kind of synthetic work. Thus, we cite those
references here and at www.cambridge.org/core/resources/pythonforscientists/refs/.
Use in this book of information from copyrighted sources is by permission (and is noted
either in this acknowledgments section or in the respective figure captions) or is usage believed
to be covered under Fair Use doctrine.

Data and Other Usage Acknowledgments


This work includes data from the Mikulski Archive for Space Telescopes (MAST) (e.g., in
Chapter 1). STScI is operated by the Association of Universities for Research in Astronomy,
Inc., under National Aeronautics and Space Administration (NASA) contract NAS5-26555.
This includes data collected by the Kepler Mission. Funding for the Kepler Mission is
provided by the NASA Science Mission directorate.
This work includes output from simulations using the molecular dynamics simulation
package NAMD (Phillips et al., 2005). NAMD was developed by the Theoretical and Com-
putational Biophysics Group in the Beckman Institute for Advanced Science and Technology
at the University of Illinois at Urbana-Champaign. The official NAMD web page is at
www.ks.uiuc.edu/Research/namd/.
This work includes surface/near-surface air temperature data (e.g., in Section 7.1) that is
from National Centers for Environmental Prediction (NCEP) Reanalysis data provided by
the NOAA/OAR/ESRL PSD, Boulder, Colorado, USA, from their website at www.esrl.noaa
.gov/psd.
This work includes data from the UCI Machine Learning Repository (Dua and Graff,
2019). The repository is at https://archive.ics.uci.edu/ml.

2 Accessed January 11, 2021.


xxviii Notices and Disclaimers

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

(accessed July 14, 2021).


Acknowledgments

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

Getting Basic Tasks Done


1 Prologue: Preparing to Program

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.

1.1 What Is a Program and Why Learn to Program?


A program is a set of instructions telling a computer what to do. Every action a computer
takes, from making a calculation to displaying a graph, is ultimately controlled by a program
that a human being writes. This program consists of a file with commands. The computer
reads that file and executes the commands one at a time.
The problem is that the language the computer understands is different from the languages
that human beings know. Natural language – the language of people – is incredibly rich
and is capable of describing so much more than facts and figures. Computer languages, in
contrast, are extremely simple with very limited vocabularies and capabilities. This is because
a computer can only do a few things:
• Save values.
• Do calculations.
• Ask if something is true or false.
• Accept input (e.g., from a keyboard) and output (e.g., to a screen).
• Do a task over and over again.
In one sense, everything a computer does – whether sending an email, playing a cat video, or
modeling the Earth’s climate – is the result of many programmers breaking down whatever
complex tasks they want the computer to do into some combination of the above capabilities.
So, learning how to program means learning how to break down the task we want to do into
(very) simple pieces and how to express those tasks in a language – a programming language –
that the computer understands. As an aside, we often talk about code or coding when referring
to the task of programming. Those terms are another way of referring to the syntax of
computer languages and the task of writing programs in those languages, respectively.
For a scientist or an engineer, what is the purpose of learning to program? Few scientists
or engineers are interested in becoming software developers, and the foundations of modern
science were developed using pen, paper, and the human mind. Newton and Darwin did their

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

Figure 1.1 Light flux from Kepler-10 during quarter 4.


1.2 What Is Python and Why Learn This Language? 5

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:

1 from lightkurve import KeplerTargetPixelFile


2 data = KeplerTargetPixelFile.from_archive('Kepler-10', quarter=4)
3 data.plot(scale='log')

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.2 What Is Python and Why Learn This Language?


There are many programming languages, and every language has its own strengths and
weaknesses. But it is difficult to learn programming in the abstract. To learn programming,
we have to use some particular language. Once we learn one language, other languages are
more easily learned, but we have to start somewhere. The language we will use in the present
work is Python.
While there is no perfect programming language, the Python language is extremely power-
ful and versatile while at the same time also easily understood and learned. Code written in
Python is very clear, so clear that it almost reads like naturally spoken English. For scientists
and engineers, Python has capabilities that make it useful for analyzing data and solving
mathematically based problems. There is a large community of scientific Python users and
developers that are constantly adding to the capabilities of the language to do science. As we
go through the text, we will see these characteristics and features of Python. For now, just
trust us that Python is a good place to start.
There is, however, one additional reason for learning Python: it is free. Python is an open
source programming language, that is, a programming language whose underlying code is
itself available and open to anyone to examine and use for their own purposes. Python is free
in the sense of “freedom.” Python is also free in the sense of “no cost.” As a result, if we
have a connection to the Internet, we can obtain a copy of everything needed to run Python
programs. We can use the Python language for our own programs without worrying about
whether we can purchase a (possibly) expensive license for a specialized data analysis language
or whether a program we write today will be able to be run tomorrow if we distribute it to
others or move to another computer ourselves. After learning Python, we can be confident

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.

1.3 Software We Will Need


In this book, we will learn to write Python programs, but in order to get our computer to
run (or execute the commands of) our programs, we need a little more than the program
instruction files themselves. Python most usefully comes as part of a distribution of utility
programs and tools.
We have written this text assuming version 3.x (e.g., 3.6, etc.) of Python has been installed,
through a recent installation of the Anaconda distribution.2 Installing the Anaconda distri-
bution is preferable to installing Python from the Python Software Foundation’s website, or
to rely on the version of Python that is included with some operating systems, because the
Anaconda distribution includes packages and utility programs that are essential for scientists
and engineers.
The Anaconda distribution download page contains detailed directions on how to down-
load and install the software. We provide an up-to-date link to the page at www.cambridge
.org/core/resources/pythonforscientists/refs/, ref. 1. This edition is free to individuals and can
be installed without administrator privileges. It can be installed on the same computer or
account at the same time as another installation of Python and is available for all major
operating systems (Windows, Mac OS X, and Linux).
When installed out-of-the-box, the Anaconda distribution provides most of what
we need. Through the distribution’s tools, we can also add additional utility programs
and libraries (called packages) to the distribution, as desired. Use Anaconda Nav-
igator to install additional packages and manage packages. Up-to-date links to the
Navigator documentation and getting started guide are at www.cambridge.org/core/
resources/pythonforscientists/refs/, refs. 2 and 3 respectively.
Here is a list of additional packages that are used in the current text that might not come
with the default installation of the Anaconda distribution. In parentheses, we note which
chapters or parts of these packages are first and/or mainly used:
• cartopy (Chapter 14),
• line-profiler (Part IV),
• memory-profiler (Part IV),
• netCDF4 (Chapter 18),
• numba (Part IV),
• pytest (Section 23.3.2).
2 Most of the code in this book, particularly in the earlier chapters, will also work with Python 2.7.x. However,

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.

2.1 Example of Python as a Basic Calculator


We introduce the example in this section. The detailed description of how the example works
and why it does what it does is found in the next section (Section 2.2). When we read the
beginning examples in most of the chapters, it is okay to not understand everything (or most
things) in the examples. This is our first look at the concepts involved!
A basic calculator needs to do two tasks:
• Perform arithmetic.
• Store values for recall and reuse.

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 a Jupyter notebook, this would be:

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

1 >>> volume_cube_1 = 2*2*2


2 >>> volume_cube_2 = 3*3*3
3 >>> volume_cube_1 + volume_cube_2
4 35

In [1]: volume_cube_1 = 2*2*2


volume_cube_2 = 3*3*3
volume_cube_1 + volume_cube_2

Out[1]: 35

Figure 2.1 An example of evaluating expressions, saving values as variables, and


using variables in other expressions, using the default Python interpreter and using
a Jupyter notebook.

2.2 Python Programming Essentials


The example in Figure 2.1 illustrates the four Python programming topics we will discuss
in this chapter: expressions, operators, variables, and the interpreter itself. Whereas the
code can be executed using the default Python interpreter or in the Jupyter notebook
environment, nearly all the interactive code examples will be given using Jupyter. For the sake
of conciseness, when we show the interactive environments of the default Python interpreter,
Jupyter notebooks, and other console environments described in Section 3.2.5, we will usually
refer to them as the “interpreter.” Section 2.2.3 discusses the default interpreter and Jupyter
notebook environments in more detail.

2.2.1 Expressions and Operators


The code snippets 3*3*3 and volume_cube_1 + volume_cube_2 are examples of
expressions. Expressions are collections of values and variables (and other items, as we will
see later) that are joined together and acted on by operators.
Values are numbers written as we would expect (e.g., 3, -7.2), although to represent a
number in scientific notation we enter it in the form xey, where the x represents the number
multiplied by the power of 10 and y represents the exponent to the power of ten. Thus, the
following two columns of numbers are equivalent:
Scientific notation Python form

5.4 × 106 5.4e6


7.54 × 10−4 7.54e-4
−2.4 × 10−2 -2.4e-2
Some operators work on two elements (such as the addition (+) operator, which adds the
numbers to the left and right of the operator), whereas others work on only one element.
2.2 Python Programming Essentials 11

Table 2.1 Arithmetic operators.


Operation Symbol
Add +
Subtract −
Multiply ∗
Divide /
Integer divide //
Exponentiation ∗∗

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

www.cambridge.org/core/resources/pythonforscientists/refs/, ref. 17.


12 2 Python as a Basic Calculator

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

2 http://stackoverflow.com/a/5365702 (accessed October 19, 2020).


2.2 Python Programming Essentials 13

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:

volume_cube_1 = volume_cube_1 + 100

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:

volume_cube_1 = volume_cube_1 + 100

an accumulator, because the variable volume_cube_1 accumulates value; more is added


onto the existing value. If the variable loses value, as here:

volume_cube_1 = volume_cube_1 - 100

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:

In [1]: volume_cube_1 = 2*2*2


volume_cube_2 = 3*3*3
sum_cubes = volume_cube_1 + volume_cube_2
volume_cube_2 = 4*4*4
sum_cubes

Out[1]: 35
2.2 Python Programming Essentials 15

Instead of calculating volume_cube_1 + volume_cube_2 and outputting the result


to the screen, we save it to sum_cubes. Then, we change volume_cube_2 and output
sum_cubes to the screen.
Why is sum_cubes unchanged even when volume_cube_2 is changed in the fourth line
of In [1]? The value of sum_cubes does not change when volume_cube_2 changes,
because Python does not go back and reevaluate the volume_cube_1 + volume_cube_2
expression using the new volume_cube_2 value. Put another way, the line that assigned
sum_cubes is not an algebraic expression that is true as the value of volume_cube_2
changes. Rather, the line that assigned sum_cubes does the calculation and makes the
assignment, and from that point on, Python only knows that sum_cubes has a value of
35. Python does not know, after sum_cubes is assigned, how sum_cubes was calculated.
Whereas our previous code examples have contained two variables or less to the right of
the equal sign, we can have any number of variables in a line of code on the right-hand side
of the equal sign. We also do not need the blank spaces on either side of the equal sign.
Thus, a = 2 and a=2 work equally well (pun intended ). However, the addition of blank
spaces between tokens – such as numbers, operators, and the equal sign – greatly improves
the readability of longer expressions, so their use is preferred.
When using Python as a calculator, we will probably use a limited number of variables,
so it is probably fine to use a single letter for our variable names. But, it makes more sense
to name variables something descriptive in order to make it easier to understand what the
variable contains. In later chapers, our variable names will become more descriptive.
Python variable names must begin with a letter or underscore. Letters and underscores
can also be used in other parts of the variable name, as can numerals.3 Python is also
case-sensitive, so the variable name Volume and volume refer to two different variables.
When we have multiple words in a Python variable name, we usually separate them by
underscores (as we see in the above example). We will learn about exceptions to this rule
later on.
To see what the contents of a variable are, just type in the name of the variable:

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.

2.2.3 The Python Interpreter


As we saw earlier, to use Python as a basic calculator, there are multiple environments we can
use. The two we look at here are:
3 The reference for this portion, https://docs.python.org/3/reference/lexical_analysis.html#identifiers (accessed

January 2, 2021), also describes nuances to these rules.


Other documents randomly have
different content
107. Año 1540. El Magnífico Caballero Pero Mexía
(1500-1550) nació en Sevilla, donde aprendió latín;
en Salamanca, leyes. Esgrimía diestramente y se
carteaba con Vives en latín elegante. Fueron
muchas veces premiados sus versos, agudos y
dulces. Trató mucho á don Fernando Colón, á don
Baltasar del Río, obispo de Escalas, que despertó en
Sevilla las buenas letras. Llamábanle el astrólogo
por su afición á las matemáticas y astrología.
Sobrevínole una gran enfermedad de la cabeza que
le duró toda su vida. Fué alcalde de la Hermandad
del número de los hijodalgos, contador de S. M. en la
Casa de la Contratación, y veinticuatro. Comía poco
y no dormía más de cuatro horas. Nombróle Carlos
V su cronista (1548). Murió de cincuenta años,
siendo enterrado en Santa Marina. Celebróle con un
epitafio Arias Montano, que le tuvo en su mocedad
por padre y maestro. Fué uno de los escritores más
celebrados en su tiempo, y aun hoy en día de los
más eruditos y sabrosos, de estilo sencillo y claro,
apacible y castizo. Escribió la Silva de varia lección,
Sevilla, 1540, obra que declara muchos puntos de
erudición, á la manera de las Noches Áticas, de Aulo
Gelio, muy celebrada y traducida en varias lenguas.
Historia imperial y cesárea, esto es, de Carlos V,
Sevilla, 1544. Colloquios ó diálogos, Sevilla, 1547.
Laus Asini: ad instar Luciani et Apuleii, Sevilla, 1547.
Parenesis ó exhortacion á la virtud, de Isócrates,
traducida de la versión latina de Rodolfo Agrícola.
Fragmentos y Memorias, que quedaron en la
biblioteca de Gonzalo Argote de Molina.

108. La biografía y retrato véase en F.co Pacheco y M. Pelayo, Ilustr.


esp. Rodrigo Caro, en los Claros varones, dice que nació en 1500, y
que le consultaban pilotos y mareantes, que le escribieron Ginés de
Sepúlveda y Erasmo (Epíst., l. 25, 26, á su hermano Cristóbal, y á él
la 27). Fué alabado de los más famosos escritores. Al fin del Ms.
colombino de la Hist. de Carlos V se lee, de puño y letra de
Colmenares: "Murió Pero Mexía, autor desta historia, año de 1551...
Fué infelicidad de este príncipe y de la nación española que no la
acabase, para que no hubiera caído en manos de fray Prudencio de
Sandoval, ya que el señor Rey D. Felipe II no advirtió en honor de
su padre encargarla á don Diego Hurtado de Mendoza, con que
tuviéramos la mejor historia por el asunto y por el escritor, que acaso
hubiera en el mundo, fuera de las sagradas...". Rosell: "Mexía, como
historiador, fuera de las lisonjas que prodiga al César y que le hace
llamar siervos á los vasallos, adolece de cierto amaneramiento en la
elaboración de los períodos y en el uso de los sinónimos, con que,
sin duda, pretende esclarecer más las ideas; pero es buen hablista,
escritor claro y vigoroso; hábil en la manera de disponer su asunto.
No deja de ser feliz en la elección de las palabras y no menos en el
empleo de las metáforas y comparaciones, como al referir el
incendio de Medina... Algunas veces incurre en afectación, y otras,
por evitar este defecto, se arrastra con demasiada languidez; pero
no debe olvidarse que sus largos padecimientos necesariamente
habían de debilitar su espíritu y que no habiéndole dejado la muerte
terminar su obra, tampoco le daría tiempo para perfeccionarla".
El Docto Cavallero Pedro Mexía.

(Pacheco. Libro de Retratos)


Silva de varia lección, Sevilla, 1540, 1542; Zaragoza, 1542;
Amberes, 1544; Sevilla, 1547; Zaragoza, 1547; Venecia, 1550 (en
ital.); Valladolid, 1551; París, 1552; Venecia, 1553; Zaragoza, 1554,
con 5.ª y 6.ª partes anónimas; Amberes, 1555; Lyon, 1556 (dos
edic., cast. é ital.), 1557, 1558, 1561 y 1563; Sevilla, 1563; Amberes,
1564; Londres, 1566-1569 (en ingl.); Sevilla, 1570; Lérida, 1572;
Sevilla, 1587; Madrid, 1602; Amberes, 1604; Madrid, 1643, 1662,
1673, con la traducción de la Parenesis. Mambrini da Jabrino tradujo
al italiano las 4 partes, Lyon, 1556. Jerónimo Giglio añadió una
continuación, Seconda silva, Venecia, 1573. Reprodújose, en
Venecia, Silva rinovata di varia lectione di Francesco Sansovino,
Mambrino Rosseo et Bartholomeo Dionigi, 1616. Según Andrés
Escoto, se tradujo al francés y se le añadieron varios libros. Antonio
Verdier, autor de la Bibliotheca Gallica, cita una traducción de Lyon,
1576, después dos veces reimpresa. En 1643 publicó Claudio
Grugnet una versión de la Silva (Rathomayi, por Jorge Loysellet),
que comprende además tres diálogos de nuestro autor. Hay
ediciones francesas de la Silva de 1570, 1577 y 1580 y otras
muchas, según Verdier. Nic. Antonio dice haber visto una obra
francesa titulada Leçons diverses de Guyon de la Nauche suivant
celles de P. Messia et de du Verdier, 2 vols., Lyon, 1610. Se hicieron
dos traducciones al inglés y una al alemán (Ticknor). Historia
imperial y cesárea, Sevilla, 1544, 1545, 1547; Basilea, 1547 (en
latín); Amberes, 1552; Sevilla, 1554; Amberes, 1561; Venecia, 1561;
Sevilla, 1564; Amberes, 1578. Tradújola al italiano Alfonso de Ulloa
y Luis Dolce. Coloquios ó diálogos, Sevilla, 1547; Amberes, 1547;
Zaragoza, 1547; Sevilla, 1548, 1551; Venecia, 1557 (en ital.);
Amberes, 1561; Sevilla, 1562; Venecia, 1565; Sevilla, 1570, 1580,
1598; Madrid, 1767, con la Parenesis. Laus Asini: ad instar Luciani
et Apuleii, Sevilla, 1547; Amberes, 1547, 1566; Sevilla, 1570, 1576.
Hay versión francesa anónima é italiana de Alfonso de Ulloa:
Raggionamenti di Pietro Messia, Venecia, 1557, 1565, con la
Filosofía de Juan de Xarava, traducida por el mismo Ulloa. Historia
del Emperador Carlos V, empezada tres años antes de su muerte
(1549) y dejada en el libro V: hay tres copias en la bibl. del Conde-
Duque de Olivares y otra que tenía Diego de Colmenares, hoy de la
Bibl. Colombina. Sandoval se aprovechó mucho de ella sin citarla.
En 1852 Cayetano Rosell publicó lo tocante á las Comunidades (que
forma el l. 2 de la Hist. de Carlos V) en la Bibl. de Autor. Esp., ts. XXI
y XXVIII. Pero Mexía, Relación de las comunidades de Castilla, Bibl.
de Aut. Esp., t. XXI. Consúltense: M. Menéndez y Pelayo: El
magnífico Caballero P. M., en La Ilustración Española y Americana
(1876), páginas 75, 76, 123, 126. F.co Pacheco, Libro de Retratos, y
copiado por L. Villanueva, en Semanario Pintoresco Español de
1844, págs. 405, etc.

109. Año 1540. Comedia Fenisa, Sevilla, 1540, ó, como puso


Moratín, Coloquio de Fenisa, y así se publicó en Valladolid, 1588,
reimpresa por Gallardo en El Criticón, núm. VII, Madrid, 1859;
Salamanca, 1625 (Bibl. Nac.), reimpresa por Bonilla en la Revue
Hispanique, 1912. "Llama extraordinariamente la atención, dice
Bonilla, que Moratín dijese de esta Comedia que "está escrita... con
poca invención y ninguna elegancia; no merece particular examen".
Es, por el contrario, una de las piezas más lindas del viejo
repertorio, y se distingue por la fluidez de su versificación y por la
delicadeza de su espíritu, aunque ciertamente la acción sea bien
sencilla y breve. Así lo comprendió también el pueblo, y no se
explicaría de otro modo que la obrita hubiese podido subsistir hasta
bien entrado el siglo XVII, cuando la exuberante lozanía de Lope y
sus continuadores había borrado casi por completo el recuerdo de
las antiguas farsas". En el códice de la Bibl. Nac., Colección de
autos sacramentales, loas y farsas del siglo xvi, hay un Colloquio de
Fenisa á lo divino (núm. 65) y otro de Fide ypsa (núm. 66), calcados
sobre el anterior y conservando muchos versos del original. Dicha
Colección fué publicada por L. Rouanet en la Bibliotheca Hispánica,
ts. V, VI, VII y VIII.

Las preguntas que el emperador Adriano..., Burgos, 1540.—Jorge


de Bustamante, natural de Santo Domingo de Silos, publicó Justino
claríssimo abreviador de la historia general del famoso y excellente
historiador Trogo Pompeyo, Alcalá, 1540; Amberes, 1542, 1586,
1599. Libro del Metamorphoseos y fábulas del excelente poeta y
philósofo Ovidio (Salvá); 2.ª ed., Sevilla, 1550 (Salvá); Amberes,
1551, 1595; Madrid, 1622. Gaulana, comedia en coplas (Hern.
Colón).—Hugo de Celso publicó Las leyes de todos los reynos de
Castilla: abreviadas y reduzidas en forma de Repertorio decisivo por
orden del A. B. C., Alcalá, 1540; Medina, 1553.—El valenciano
Dionisio Clemente publicó Don Valerian de Hungría, Valencia,
1540.—Pongo en 1540 la Relación del Sitio del Cuzco, y principio de
las guerras civiles del Perú hasta la muerte de Diego de Almagro
(1535 á 1539), Ms. de la Bibl. Nac., publicado en Madrid, 1879.
Varias relaciones del Perú y Chile (Libr. rar. y curiosos).—
Bernardino Daza, estudiante legista, de Valladolid, publicó en 1540
y 1548 Los emblemas de Alciato Traduzidos en rhimas Españolas.
Las Instituciones imperiales, de Justiniano, elegantemente vertidas
del latín, Tolosa, 1551; Salamanca, 1614.—Examen de la
Composición Theriacal de Andromacho, traducida de Griego y Latín
en Castellano y comentada por el licenciado Liaño, Burgos, 1540.
—J. Panzano escribió Anales de Aragón desde el año 1540... hasta
el año 1558, Zaragoza, 1705.—Antonio Polo, aragonés, de
Alfocea, publicó Grammaticae annotationes in IV et V Ant.
Nebrissensis libros, Zaragoza, 1540, 1555. Caenotaphium in obitu
Caroli V Imp. Caesaraugustae celebrato, ibid., 1558.—Quaestiones
logicae sec. viam Realium et Nominalium, Alcalá, 1540.—Fray
Francisco Ruiz, de Valladolid, benedictino, publicó Index... in
Aristotelis Stagiritae opera, quae extant, y Judicium de Aristotelis
operibus, 2 vols., Sahagún, 1540. Regulae CCCXXXIII intelligendi
Sacras Scripturas, Lyon, 1546.—Jerónimo Sempere publicó la
Primera parte de la Carolea, trata las victorias del Emperador Carlos
V, Valencia, 1540. Segunda parte de la Carolea, Valencia, 1540.
Caballería celestial de la Rosa fragante, Valencia, 1554; Amberes,
1554: libro de caballerías á lo divino. Segunda Parte de la cauallería
de las hojas de la Rosa Fragante, Valencia, 1554. Primera y
segunda parte de la Carolea, Valencia, 1560.—Luis Vasseo, autor
de las más antiguas tablas anatómicas, publicó In Anatomen
corporis humani tabulae quatuor, 1540.—Luis de Villalonga,
mallorquín, canónigo de Mallorca, publicó De Legatis, Alcalá, 1540.
110. Año 1541. Gregorio Silvestre Rodríguez de
Mesa (1520-1569) nació en Lisboa, adonde
acababan de llegar de Zafra su padre el doctor J.
Rodríguez, llamado para médico del rey de Portugal
don Juan III, y su madre, que ya iba preñada, doña
María de Mesa. El año 1527, viniendo la infanta
doña Isabel de Portugal á casarse con el emperador
Carlos V á Castilla, acompañóle como médico el
dicho doctor, trayendo á Gregorio Silvestre de siete
años, el cual, á los catorce de edad (1534), entró al
servicio de don Pedro, conde de Feria, y en su casa
se aficionó á las poesías de Garci-Sánchez de
Badajoz, que la frecuentaba, dándose además á la
música de tecla. Á los veintiocho de edad comenzó á
tener nombre entre los que se preciaban de
componer los versos españoles que llamaban
Ritmas antiguas y los franceses Redondillas, á los
cuales se dió tanto por el amor que tuvo á Garci-
Sánchez, á Bartolomé de Torres Naharro y don Juan
Fernández de Heredia, que no pudo ocuparse en las
Composturas italianas, que Boscán introdujo en
España en aquella sazón, y así imitando á Cristóbal
de Castillejo dijo mal de ellas en su Audiencia de
Amor. Pero después, con el discurso del tiempo,
viendo que ya se celebraban tanto los sonetos,
tercetos y octavas, compuso algunas cosas dignas
de loa, y si viviera más tiempo, fuera tan ilustre en la
poesía italiana como lo fué en la española. En 1541,
viviendo en Montilla, ganó por oposición el cargo de
organista de la catedral de Granada, contrayendo
después la obligación de escribir cada año para las
fiestas nueve entremeses y muchas estancias y
chanzonetas. Casó con la guadixeña Juana de
Cazorla, teniendo de ella varios hijos, entre ellos
Juan (1547), Luis (1552), Paula (1567) y Mayor
(1569). Era hombre de muy agudo ingenio y donaire
y muy estimado en la ciudad. Fué muy amigo de
Barahona de Soto, decidido italianista. Murió el
1570, de cincuenta años, de una calentura
pestilencial con tabardete. Escribió muchas obras
amorosas y no menos obras espirituales por su
cargo de organista, obras morales, una glosa á las
coplas de Jorge Manrique y á otras muchas, y
gloriábase de ser glosador más que poeta.
111. Publicaron sus Obras la viuda, doña Juana de Cazorla, y sus
hijos, Granada, 1582, con su vida, escrita por Pedro de Cáceres y
Espinosa; Lisboa, 1592; Granada, 1599. Poema de Proserpina,
Granada, 1599. Discurso, de Pedro de Cáceres y Espinosa, en sus
Obras: "Nació Gregorio Silvestre en Lisboa, en el año de 1520, entre
los dos últimos días del dicho año, que tienen la advocación de los
dos Santos, por los cuales llamado así. Yendo su madre doña María
de Mesa, preñada desde Zafra, donde antes vivía, por haber sido el
Dr. J. Rodríguez, su padre, llamado entonces para Médico del Rey
de Portugal, y estuvieron en servicio del Rey hasta el año de 27, que
viniendo la Infanta doña Isabel de Portugal á casarse con el
Emperador Don Carlos V á Castilla vino por su Médico el dicho
Doctor, trayendo á Gregorio Silvestre de siete años, como parece en
el privilegio que en este mismo año les concedió el Emperador á
ellos y á sus descendientes. Siendo Silvestre de casi catorce años
vino en servicio de Don Pedro, conde de Feria, do á la sazón
florecía entre los Poetas Españoles Garci-Sánchez de Badajoz; y
como siempre la casa del Conde fuese llena de curiosidad, y
visitada con los escritos de aquel célebre Poeta, participó tanto de lo
uno y de lo otro, que se preciaban de componer los versos
Españoles que llaman Ritmas antiguas, y los franceses Redondillas.
Á las cuales se dió tanto, ó fuese por el amor que tuvo á Garci-
Sánchez y á Bartolomé de Torres Naharro y á D. Juan Fernández de
Heredia, á los cuales celebraba aficionadamente, que no pudo
ocuparse en las Composturas Italianas que Boscan introdujo en
España en aquella sazón. Y así, imitando á Cristóbal de Castillejo,
dijo mal de ellas en su Audiencia (de Amor). Pero después, con el
discurso del tiempo, viendo que ya se celebraban tanto los Sonetos
y Tercetos y Octavas... compuso algunas cosas dignas de loa: y si
viviera más tiempo, fuera tan ilustre en la Poesía Italiana, como lo
fué en la Española. Con todo eso intentó una cosa bien célebre, que
fué poner medida en los versos Toscanos, que hasta entonces no se
les sabía en España: la cual pocos días antes intentó el cardenal
Pedro Bembo en Italia; como parece en sus Prosas, y lo refiere
Lodovico Dolche en su Gramática. Y que en España no se supiesen,
ni la trujesen los que trujeron la Poesía Toscana á ella, parece en
que Castillejo aún no supo la medida Española de arte mayor; pues
queriendo conferir la una y la otra, introduce á Juan de Mena
diciendo de las Trovas Italianas: "Juan de Mena, cuando oyó | La
nueva trova pulida, | contentamiento mostró; | Caso que se sonriyó |
Como de cosa sabida. | Y dijo: "según la prueba, | Once sílabas por
pie | No hallo causa por qué | Se tenga por cosa nueva, | Pues yo
también las usé". De suerte que Castillejo quiere probar que las
composturas de Juan de Mena y Juan Boscán son una misma, pues
constan de once sílabas... por no entender la medida de los pies; la
cual se descubrió en España en esta sazón; y en Granada Silvestre
fué el que la descubrió... y por esto se dijo dél: "Y que por vos los
versos desligados | De la Española Lengua, é Italiana | Serán con la
medida encadenados; | Deberos ha de aquí la castellana | Más que
la Griega debe al grande Homero | Y al ínclito Virgilio la Romana".
De aquí ha venido la medida de los endecasílabos á hacerse en
España por jambos tan comúnmente que no hay quien la ignore...
Murió en el año de 1570 siendo de cincuenta años, poco después
de la rebelión de Granada, de una calentura pestilencial con
tabardete. Murió también el mayor de sus hijos en aquella sazón; y
vive el menor. De sus hijas la una entró Monja, sin dote, porque era
diestra en la Música de tecla, y hacía versos aventajadamente. Las
otras quedaron con su madre. Fué Silvestre de agudo ingenio; y en
conversación hablaba muy discretamente, casi siempre con dichos
agudos y donosos. Hablando una vez á ciertos amigos en compañía
de Juan Latino, dicen que habló á todos y no á él... y quejándose
Juan Latino dello, dicen que respondió: "Perdone, Señor Maestro,
que entendí que era sombra de uno destos Señores". Dícese
también que uno de los que entonces componían en Granada le
hurtó un Soneto, y vínoselo á enseñar por proprio, y preguntarle qué
tal le parecía... "¿Qué le parece?—Que me parece". Disgustado con
el Conde de Miranda porque le hablaba de vos, no le había visitado
muchos días, y que como una vez le encontrase el Conde en la
calle, le dijo: "—Señor Silvestre, ¿por qué no vais á mi casa vos?—
Señor, por eso". De lo cual se rió el Conde, y entendiéndole procuró
emendarse de ahí adelante... Otros muchos y muy discretos
(donaires) hay suyos, que por ventura juntará algún curioso. La
pintura de su cuerpo y rostro fué extraña, y tanto que le llamaban
monstruo de Naturaleza, porque doquiera era notado entre muchos
hombres, aunque de estatura mediana. Era hombre descuidado de
su atavío corporal, como casi siempre lo son los que, ocupados en
mayores cosas, no se acuerdan de sí. Tuvo por Mecenas y
favorecedor de sus escritos á D. Alonso Puertocarrero, hijo del
Marqués de Villanueva: al cual hizo muchas coplas y sonetos,
aunque parecen pocos. Y á D. Alonso Benegas, al cual hizo una
elegía á la muerte de su mujer... Tuvo por particulares amigos los
que entonces eran famosos en Granada, el singular abogado Luis
de Berrío; á D. Diego de Mendoza, y á Fernando de Acuña, honra
de la Poesía de España; el Maestro Juan Latino, doctísimo en la
Gramática Latina y Griega; el gran traductor Gaspar de Baeza, y el
Bachiller Pedro de Padilla, habilidad rara y única en decir de
improviso, y á pocos inferior en escribir de pensado; y al Licenciado
Luis de Castilla, que le escribió una Carta, á la cual respondió con
otra; y al Licenciado Josef Fajardo, hombre insigne en las
Matemáticas y Lenguas Latina y Griega, Hebrea y Caldea y Arábiga,
del cual hay ciertos sonetos en loa de Silvestre, y al Licenciado
Macías Bravo, y otros muchos que escribieron en su loor algunos
versos. Escribiéronle Cartas Poéticas el famoso Pedro de Padilla, y
George de Montemayor, y Francisco Farfán, el indio, y la que más
se estimó en aquellos tiempos, fué la de Luis Barahona de Soto, el
cual también fué uno de sus particulares amigos. Parte de sus obras
se han conservado, y parte están perdidas. Escribió muchas obras
espirituales, así por ser él aficionado á religión, como por darle
ocasión la iglesia mayor, donde era organista; obligándose por sólo
su gusto cada año á hacer nueve Entremeses y muchas estancias y
chanzonetas: en el cual oficio sucedió al famoso Maestro Pedro
Mota, complutense, y al Licenciado Jiménez, que hizo el Hospital de
Amor, que imprimió por suyo Luis Hurtado de Toledo; que éstos
también tuvieron cargo de escribir estos Entremeses para las fiestas
más célebres de la iglesia mayor; aunque al uno y al otro supo
aventajarse sin comparación alguna. Escribió Obras morales
muchas, una glosa á las coplas de D. Jorge Manrique. Glosó otras
muchas cosas, y tuvo para esto particular ingenio, más que para
otra cosa; y así lo solía él decir, que no era Poeta, sino glosador.
Escribió muchas obras amorosas, teniendo por sujeto casi desde su
niñez á una dama llamada doña María, cuya calidad, por razonable
respeto, no se explica. Murió esta Señora el mismo año que
Gregorio Silvestre, mes y medio antes que él... Sintió mucho
Gregorio Silvestre la muerte de doña María; y así dicen que se
determinó á hacer muchas canciones á su muerte á imitación del
Petrarca; y pienso que hizo una ó dos... y como murió tan presto no
pudo pasar adelante con su intento. Está enterrado en la iglesia del
Carmen". Epitafio: "Yace en esta iglesia chica | Y entre sus piedras
aquel | De quien la fama infiel | Más entiende que publica. | Mas
pues ella no lo explica, | Pregúntaselo al Laurel, | Al Moral, Lirio y
Clavel, | Y á mil Glosas que por él | Hacen nuestra España rica". Las
obras de Silvestre están divididas en cuatro libros. El libro I contiene:
Diez Lamentaciones, que acaban en el fol. 23; cinco sátiras; multitud
de glosas, canciones, etc., todo con coplas castellanas. El libro II:
Fábula de Dafne y Apolo; Píramo y Tisbe; La visita (de cárcel) de
Amor; La residencia de Amor. El libro III: Glosas y canciones de
moralidad y devoción; dos romances devotos; glosa sobre las coplas
de don Jorge Manrique. El libro IV contiene los versos que dicen á la
larga y al través, endecasílabos, etc.; sonetos, y la Fábula de
Narciso, en octavas.

Gregorio Silvestre, Poesías, Bibl. de Aut. Esp., ts. XXXII y XXXV.


Consúltense: D. García Peres, Catálogo razonado biográfico y
bibliográfico, etc., Madrid, 1890. H. A. Rennert, en Modern
Language Notes (1899), t. XIV, cols. 457-465. F. Rodríguez Marín,
Luis Barahona de Soto, etc., Madrid, 1903, págs. 32-35.

112. Año 1541. Florián de Ocampo (1499?-1555?),


zamorano, hijo de Lope Docampo, que lo fué de
Diego de Valencia y de la portuguesa Sancha Garzia
Docampo, estudió en Alcalá con Nebrija y otros
maestros, fué nombrado canónigo de Zamora y por
Carlos V cronista imperial. Las Cortes de Castilla de
1555 pidieron al Emperador se le señalase sueldo
para que pudiese acabar su historia, sin ocuparse en
las obligaciones de su canonjía. Ambrosio de
Morales alaba su mucha diligencia y trabajo y la
grandeza de su estilo, continuando su obra. Dañóle
el crédito que dió al seudo Beroso, publicado por
aquel tiempo. De las cuatro partes que pretendía
escribir, tan sólo un pedazo de la primera acabó con
el título de Los quatro libros primeros de la Crónica
general de España, Zamora, 1544. Quiso llegase
esta primera parte hasta Jesucristo; pero dejóla en
los Escipiones, y se publicó en Zamora, 1544; con el
quinto libro en Medina, 1553. No es gran historiador
cuanto al fondo, sus noticias son poco seguras y el
estilo nada tiene de particular.
113. Estos cuatro, de los cinco libros, se los sacó un impresor,
según da á entender Florián en carta á Juan de Vergara. Dice que
enmendó muchas cosas para la edición siguiente; pero habiendo
fallecido antes de darla, fué publicada, completa ya en sus cinco
libros, por Ambrosio de Morales, en Alcalá, 1578; Valladolid, 1604.
Había antes publicado por primera vez la crónica llamada de Alfonso
el Sabio, en 1541. Cita á Juan de Viterbo y su Beroso y á Manethon,
obras ya desechadas antes de él. Véase Nicerón, Hommes illustres,
París, 1730, t. XI, págs. 1-2, y t. XX, págs. 1-6. Las quatro partes
enteras de la Crónica de España, de Alfonso X, Zamora, 1541;
Valladolid, 1604; extracto del ms. original de la Coronica ó grande
Estoria general de Espanna. En fabla antigua comenzada á copilar
no tempo do Rey Don Alfonso X, precioso códice acabado en la era
de 1403, hoy propiedad del librero Vindel, Madrid; está en galaico-
portugués. Los quatro libros primeros de la Crónica general de
España, Zamora, 1544; Zamora (sin fecha); Medina, 1553, con el 5.º
libro; Alcalá, 1564. Los cinco libros primeros De la Coronica general
de España que recopilava el maestro Florián de Ocampo, Alcalá,
1578; Valladolid, 1604. Crónica general de España por Florián de
Ocampo, Ambrosio de Morales y Fr. Prudencio de Sandoval, Madrid,
1791-93, 15 tomos. Consúltese: G. Cirot, Les Histoires générales
d'Espagne entre Alphonse X et Philippe II (1284-1556), Bordeaux,
1905, págs. 97-147. Su biografía, en la Biblioteca de escritores que
han sido individuos de los seis colegios mayores, por José de
Rezabal y Ugarte, págs. 233-8; y en la impresión de su Crónica de
1791.

114. Año 1541. Blasco de Garay, racionero de Toledo, publicó Dos


Cartas en que se contiene, cómo sabiendo una señora que un su
servidor se quería confessar: le escribe por muchos refranes,
Toledo, 1541, con otras dos, una que dice le dió Juan Vázquez de
Ayora; otra impresa en Toledo. Salió la obra con el título de Cartas
en refranes, con las coplas de Jorge Manrique, los refranes de H.
Núñez y con los de Mal-Lara: Toledo, 1541; 1545 (sin lugar);
Venecia, 1553; Medina, 1569; Alcalá, 1570; Sevilla, 1575; Amberes,
1577; Sevilla, 1577; Huesca, 1581; Alcalá, 1581; Huesca, 1584;
Alcalá, 1588; Madrid, 1598; Bruselas, 1608, 1612; Lyon, 1614;
Madrid, 1614, 1617, 1619; Lérida, 1621; Madrid, 1632, 1864.
Arcadia de Jacobo Sannazaro, Toledo, 1547, hecha la prosa por el
canónigo Diego López de Toledo y el verso por el capitán Diego de
Salazar: así lo dice el editor Garay en el prólogo, añadiendo que él
mismo retocó los versos; ibidem, 1549; Salamanca, 1578. Inéditas
quedaron otras traducciones de la Arcadia por Juan Sedeño y por
Jerónimo de Urrea (Gallardo, núms. 3900 y 4120); los manuscritos,
en la Bibl. Nacional.

Martín Laso de Oropesa, de este pueblo, canónigo burgalés,


secretario del ilustrísimo cardenal don Francisco de Mendoza,
obispo de Burgos, publicó el grandilocuente libro que tituló La
Historia que escribió en latín el Poeta Lucano, sin lugar ni año de
impresión; después en Lisboa, 1541. Las ediciones de Burgos, 1578
y 1588, llevan además la Historia del Triunvirato, y va dirigida "al
ilustrísimo señor don Antonio Pérez, secretario del estado de la
Magestad Cathólica del Rey don Phelippe Segundo". Tanto la
traducción como la historia original suya están escritas en estilo
elevado, magnilocuente, cual lo pedía el poeta traducido; pero sin el
menor rastro de mal gusto. Gran fidelidad en la versión, propiedad
en las voces, muchas poco usadas, pero de hondo casticismo; es
uno de los mejores libros escritos en romance.
Marco Aurel, natural alemán, publicó Tratado muy útil y
provechoso para toda manera de tratantes y psonas afficionadas al
contar, Valencia, 1541. Libro primero, de arithmética algebrática, en
el qual se contiene el arte Mercantival, con otras muchas Reglas del
arte menor, y la Regla del Algebra, vulgarmente llamada Arte Mayor
ó Regla de la cosa: sin la qual no se podrá entender el décimo de
Euclides ni otros muchos primores, assí en Arithmética como en
Geometría, Valencia, 1552.—Antonio Barba tradujo el Diálogo, de
Sepúlveda: Diálogo llamado Demócrates compuesto por el doctor
Juan de Sepúlveda, Sevilla, 1541.—El doctor Damián Carbón de
Mallorca publicó el Libro del arte de las Comadres ó madrinas y
del regimiento de las preñadas y paridas y de los niños, Mallorca,
1541: primera obra de obstetricia en España y de las más notables
de la antigüedad.—Fray Juan de la Cruz, dominico talaverano,
publicó La Historia de la Iglesia, que llaman Eclesiástica y Tripartita,
Lisboa, 1541; Coimbra, 1554. Diálogo sobre la oración...,
Salamanca, 1555. Suma de los Mysterios de la Fee de Fr. F.co
Titelman, ibid., 1555. Chronica de la Orden de Predicadores, Lisboa,
1567. Treinta y dos Sermones, Alcalá, 1568. Epitome de Statu
Religionis, Toledo, 1611; Madrid, 1613, 1622. Directorium
conscientiae, Madrid, 1620; Toledo, 1624, 1626, 1628, 1631; Madrid,
1648.—Enquiridio ó manual del cavallero christiano, de Erasmo,
Lisboa, 1541.—Cristóbal de Escobar publicó De causis corruptae
eloquutionis, 1541. De verbis exceptae actionis. De verbis
impersonalibus, etc. De naturalium nominum ratione lucubratio. De
viris latinitate praeclaris in Hispania.—La Historia Eclesiástica de
Eusebio Cesariense, Lisboa, 1541.—Francisco de la Fuente
publicó Grammatica Methodus, Alcalá, 1541.—Libro artificioso para
todos los pintores, Amberes, 1541.—Luis Lobera de Ávila, médico
de Carlos V, publicó Vergel de Sanidad (¿Alcalá, 1541?). Remedio
de cuerpos humanos y silva de experiencias y otras cosas
utilíssimas, Alcalá, 1542; Venecia, 1566. Libro de pestilencia
curativo y preservativo, ibid., 1542. Antidotario muy singular de
todas las medicinas usuales y la manera cómo se han de hacer,
ibid., 1542. Libro de las quatro enfermedades cortesanas, que son
Catarro, Gota arthética, Sciática, Mal de piedra..., Toledo, 1544.
Libro de experiencias de medicina, Toledo, 1544. Regimiento de la
salud; de la esterilidad de hombres y mugeres, y enfermedades de
los niños, Valladolid, 1551. Don Alonso Ruiz de Virués († 1549)
nació en Olmedo, fué benedictino, doctísimo teólogo y perito en
lenguas orientales; predicador de Carlos V, á quien acompañó en el
viaje de 1540 á 1541 á Flandes y Alemania; obispo de Canarias y
erasmista, procesado por la Inquisición (1537, de levi, ad cautelam).
Escribió, con ocasión del casamiento de Enrique VIII de Inglaterra
con Ana Bolena, Tractatus de matrimonio Regis Angliae, con
Philippicae Disputationes viginti adversus Luterana dogmata, per
Philippum Melanchthonem defensa, Antuerpiae, 1541. Collationes
septem cum Erasmo Roterodano habitae (Nic. Ant.). Véase M.
Pelayo, Heterodoxos, t. II. Vergara: "Erasmi usque ad invidiam
percupidus". Vives: "homo [Greek: γνησίος ὲρασμϰός]". Al. Valdés:
"aventajando á los demás en erudición y piedad, no podía menos de
favorecer las buenas letras y la sincera religión". Bonilla cree que
tradujo parte de los Coloquios de Erasmo (véase Luis Mexía, 1528).
—Fray Miguel de Salinas (1501-1567), jerónimo zaragozano,
publicó la primera Rhetórica en lengua castellana, Alcalá, 1541, para
uso de predicadores. Tratado de la forma que se debe tener en leer
los autores, ibid., 1541. Tratado para saber bien leer y escrivir,
pronunciar y cantar letra assí en latín como en romance, Zaragoza,
1551. Libro apologético que defiende la buena y docta
pronunciación que guardaron los antiguos, Alcalá, 1563; Madrid,
1587. Primera Parte de la Ortografía y origen de los Lenguajes,
Alcalá, 1563, 1567. Manera para poner en ejercicio las reglas de
retórica. Tratado de los avisos en que consiste la brevedad. Origen
de los lenguajes, Alcalá, 1567. Dejó mss.: Libro de poesía y
espirituales conceptos. Prontuario para saber las costumbres y usos
del monasterio de S. Engracia en Zaragoza.—Breve summa lamada
Sossiego y descanso del ánima, Alcalá, 1541.

115. Año 1542. Martín de Azpilcueta ó el doctor


Navarro (1492-1586), por haber nacido en
Barasoain del Valle de Orba, cerca de Pamplona,
hijo de Martín de Azpilcueta y de doña María, el más
célebre de nuestros canonistas y moralistas, de la
misma familia de San Francisco Javier, fué canónigo
regular de Roncesvalles, estudió en Alcalá y Tolosa,
donde enseñó Cánones, así como en Cahors, y á
pesar de ser extranjero le quisieron nombrar
consejero del Parlamento de París, cosa que no
aceptó. Volvió á España y obtuvo por oposición la
cátedra de prima de Cánones en Salamanca, que
regentó catorce años; pero llamado por Juan III de
Portugal, enseñó otros diez y seis en la Universidad
de Coimbra, renunciando á la mitra que le ofrecía.
Convencido de la inocencia del Arzobispo de Toledo,
Carranza, Felipe II le nombró su abogado en
Valladolid y en Roma, donde vivió el resto de sus
días, ayudando al Cardenal Penitenciario apostólico
por orden de Pío V y siendo obsequiado por
Gregorio XIII que le visitaba en su casa, por su
discípulo el cardenal Pedro Deza y por toda la Corte
pontificia. Varón sapientísimo y santísimo por su
mortificación y virtudes, tenía un juicio maravilloso
para desenmarañar cuestiones morales y una
portentosa erudición. Sixto V le hizo extraordinarios
funerales y el pueblo le honró en su muerte como á
santo. Manejaba el castellano con la limpieza y brío
de los mejores de su tiempo. Son notables, entre sus
muchas y autorizadísimas obras, el Tractado de
alabanza y murmuración, Coimbra, 1542; el Tratado
de la Oración, Horas canónicas y otros divinos
oficios, Coimbra, 1545; el famosísimo Manual de
Confesores, Coimbra, 1553, el Comentario
resolutorio de usuras, Salamanca, 1556, y el
Capitulo veynte y ocho de las Addiciones del Manual
de Confessores, Valladolid, 1566.
Martín de Azpilcueta.

(Salesa lo dibuxó. D.n Mn.l Salv.r Carmona lo gravó)


Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like