0% found this document useful (0 votes)
2 views35 pages

Introduction to Python (1)

This document is a tutorial book on using Python for scientific computing, specifically designed for physics students at Brigham Young University. It builds on prior programming knowledge and aims to quickly familiarize students with Python syntax and tools necessary for their lab work. The content includes installation instructions, basic programming concepts, and practical exercises using the Anaconda distribution and the Spyder IDE.

Uploaded by

deepu_umrao
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views35 pages

Introduction to Python (1)

This document is a tutorial book on using Python for scientific computing, specifically designed for physics students at Brigham Young University. It builds on prior programming knowledge and aims to quickly familiarize students with Python syntax and tools necessary for their lab work. The content includes installation instructions, basic programming concepts, and practical exercises using the Anaconda distribution and the Spyder IDE.

Uploaded by

deepu_umrao
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

I NTRODUCTION TO P YTHON

Michael J. Ware

Department of Physics and Astronomy


Brigham Young University
I NTRODUCTION TO P YTHON
Michael J. Ware

Department of Physics and Astronomy


Brigham Young University

© 2019 Michael J. Ware, Brigham Young University

Last Revised: October 22, 2019


Acknowledgements

This book is based heavily on the book Introduction to Scientific Computing


in Python, by Lance J. Nelson and Matthew R. Zachreson at BYU Idaho. With
their permission, I’ve adapted their material to our use here at BYU Provo. In
a sort of virtuous cycle, Ross Spencer and I had previously allowed Lance and
Matthew to borrow material from our book Introduction to Matlab in the creation
of their Introduction to Scientific Computing in Python. Thus, this work is a
mix of content from the BYU Idaho Python book, our original Matlab book, and
new and modified material specific to this edition. I express sincere thanks and
acknowledgment to Ross, Lance, and Matthew for all of the work that has gone
into development this material. I’ve put my name as author of this edition to
reflect the fact that I am the one editing this particular offshoot of our combined
work.

v
Preface

This book is a tutorial for physics students to get up to speed using Python for
scientific computing as quickly as possible. It assumes that the reader is already
familiar with the basics of scientific programming in another programming lan-
guage, and does not spend time systematically going through the fundamentals
of programming. This tutorial is designed to work hand-in-hand with the BYU
Physics 430 lab manual. Each chapter in this tutorial is designed to give students
enough understanding of the Python syntax and ecosystem to tackle a specific
scientific computing lab, and in doing so will sample from a range of different
topics.
Students in the class for which the book is designed have previously taken
a three-credit introductory programming class in C++, a one-credit lab courses
introducing them to Mathematica, and another one-credit lab course introducing
them Matlab. In this book, we build on that foundation, without trying to re-teach
(at least not too much) the material already covered in prior classes. We also
present material in the order needed to complete the associated labs rather than
as a systematic and complete treatment of each topic before moving to the next.
As you find mistakes or have suggestions, send them to me at ware@[Link].

vii
Contents

Table of Contents ix

1 Numpy, Scipy, and Plotting 1


1.1 Get Anaconda Installed . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Your First Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.3 The Python Console . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.4 Variables and Data Types . . . . . . . . . . . . . . . . . . . . . . . . 3
1.5 Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.6 Float variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.7 Functions and Help . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.8 Boolean variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.9 String Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.10 Formatting Printed Values . . . . . . . . . . . . . . . . . . . . . . . 5
1.11 Functions and Libraries (Numpy) . . . . . . . . . . . . . . . . . . . 6
1.12 Numpy Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.13 Making x-y Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.14 Customizing the IDE . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2 Lists, Loops, Logic, and 2D Arrays 13


2.1 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2 The r❛♥❣❡ Function . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.3 For Loops and Shorthand Assignments . . . . . . . . . . . . . . . 14
2.4 Logical Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.5 While Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.6 2D NumPy Arrays–Matrices . . . . . . . . . . . . . . . . . . . . . . 18
2.7 Solving a Set of Linear Equations . . . . . . . . . . . . . . . . . . . 19
2.8 NumPy Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

3 Functions 21
3.1 User-defined functions . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.2 Importing User Defined Functions . . . . . . . . . . . . . . . . . . 22
3.3 Writing Readable Code . . . . . . . . . . . . . . . . . . . . . . . . . 23

Index 25

ix
Chapter 1
Numpy, Scipy, and Plotting

1.1 Get Anaconda Installed


Python is a popular general-purpose programming language that has become a
standard language for many areas of scientific computing. It is open source, and
there are many implementations of Python, many development environments
for it, and multiple versions of the programming language itself. We will use
the Anaconda distribution for Python version 3.7. The Anaconda distribution is
geared toward scientific computing, is available as a free download on all major
platforms, and comes with an integrated development environment (IDE) called
Spyder. Anaconda Python is installed on the lab computers, and we recommend
that you also install it on your personal computers so you can work at home (see
[Link]).

1.2 Your First Program


Launch the Spyder IDE. You should see a window similar to the one in Fig. 1.1.
The Spyder IDE interface is divided into three main windows:

• The code editor on the left is where you edit your Python code files (usually
with a .py extension).

• The top right pane has three default tabs: a variable explorer where you can
view current values stored in memory, a file explorer where you can browse
your files, and a help tab where you can ask questions

• The lower right pane is a console window where your output will be dis-
Figure 1.1 The Spyder IDE win-
played and you can issue Python commands directly to be evaluated.
dow.
To write your first program, press the “New File” button on the toolbar, erase any
auto-generated text so you have a blank window, and then type
♣r✐♥t✭✬❍❡❧❧♦ ❲♦r❧❞✬✮

Save your program in a new directory (where you will save all your work for this
class) with the name [Link], then click the green arrow above the editor. Spyder
may ask you in which console you’d like to execute the program. Just accept the
default values, and then look down at the console window. There you will see
some code that Spyder auto-generated to run your program, and under it should
be the output from your program:
❍❡❧❧♦ ❲♦r❧❞

1
2 Chapter 1 Numpy, Scipy, and Plotting

Congratulations, you just executed your first Python program. Change the text
string ✬❍❡❧❧♦ ❲♦r❧❞✬ to something else, and then click the green arrow again.
Notice that Spyder saves your code and executes the program again. If you get
tired of clicking the green arrow, F5 is the keyboard shortcut to save and execute
the code shown in the editor.

1.3 The Python Console


Spyder’s console window is a powerful environment called Interactive Python
(or IPython for short) where you can directly enter Python commands. Put your
cursor in the console window at the ■♥ ❬✶❪✿ prompts, type

✶✰✶

and press enter. You should see the answer, stored in a variable ❖✉t❬✶❪. You can
use this output in later calculations by typing the following at the ■♥❬✷❪✿ prompt:

❖✉t❬✶❪✰✷

Notice that your new result is stored in ❖✉t❬✷❪. IPython behaves a lot like a Mat-
lab’s command window, with a series of inputs and variable values accumulating
in the workspace. When you run your Python programs, your variables are placed
in the console’s workspace and can be accessed from the command line afterward.
With your cursor in the command window, press the Up-Arrow key, and notice
that you can access your command history with the up and down arrow keys.
The console can be useful for quick calculations or for looking at data when
debugging, but you should do most of your programming in the editor. Add the
following line to your [Link] program

✶✰✶

and run it again. Note that the answer to ✶✰✶ is not displayed in the console when
you run the program. Now switch your program to read

♣r✐♥t✭✶✰✶✮

and run it again, and note that the answer displayed in all its glory. Python
evaluates each line of code, but will not display the result of a calculation in the
console unless you ♣r✐♥t it.
As we go through the remainder of the text, type all the indented example
code into a *.py file in the editor by hand (don’t copy and paste) and execute it
using the green arrow (or the F5 keyboard shortcut). This method of interacting
with the code will help you better process and understand what each command
does. It forces you to read the code like Python will: one line at a time, top to
bottom. Also, place each command on a separate line and don’t indent any lines
of code when you type them in. Python really cares about white space. We’ll learn
more about that in the next chapter.
1.4 Variables and Data Types 3

1.4 Variables and Data Types


Variables in Python don’t need to be declared before being used. You declare a
variable and assign it a value in one statement using the assignment operator (❂),
like this

① ❂ ✷✵

(Did you type the line of code into your program and execute it? If not, do so now
and get in that habit.) This statement creates the variable ① and assigns it a value
of 20. Python didn’t print anything since we didn’t include a ♣r✐♥t command. To
convince yourself that the variable ① was defined, click on the “Variable explorer”
tab in the upper-right pane of Spyder to see that the variable exists, and has a
value of 20. Also type ① in the console window and hit enter, and note that Python
displays its value. Now add the line

① ❂ ① ✰ ✶

to your program, execute it, and look at the new value of ① to convince yourself
that the program executed correctly. Multiple variables are defined by putting the
assignments on separate lines, like this

❛ ❂ ✷
❜ ❂ ✹
❝ ❂ ❛ ✯ ❜

Sometimes you may want your program to prompt the user to enter a value
and then save the value that the user inputs to a variable. This can be done like
this:

❛ ❂ ✐♥♣✉t✭✬❲❤❛t ✐s ②♦✉r ❛❣❡❄✬✮

When you run this line of code, you will be prompted to enter your age. When
you do, the number you enter will be saved to the variable ❛.
Variable names must start with a letter or an underscore and consist of only
letters, numbers, and underscores. Variable names are case sensitive, so watch
your capitalization.

1.5 Integers
The simplest type of numerical data is an integer. Python implicitly declares
variables as integers when you assign an integer values to the variable, as we did
above. You can perform all the common mathematical operations on integer
variables. For example:
t Notice that we’ve intro-
❛ ❂ ✷✵ duced the Python com-
❜ ❂ ✶✺ menting syntax here: any
❝ ❂ ❛ ✰ ❜ ★ ❛❞❞ t✇♦ ♥✉♠❜❡rs text following the symbol ★
❞ ❂ ❛✴❜ ★ ❢❧♦❛t✐♥❣ ♣♦✐♥t ❞✐✈✐s✐♦♥ on a line is ignored by the
Python interpreter.
4 Chapter 1 Numpy, Scipy, and Plotting

✐ ❂ ❛✴✴❜ ★ ✐♥t❡❣❡r ❞✐✈✐s✐♦♥


r ❂ ❛ ✪ ❜ ★ r❡t✉r♥ ♦♥❧② t❤❡ r❡♠❛✐♥❞❡r✭❛♥ ✐♥t❡❣❡r✮ ♦❢ t❤❡ ❞✐✈✐s✐♦♥
❡ ❂ ❛ ✯ ❜ ★ ♠✉❧t✐♣❧② t✇♦ ♥✉♠❜❡rs t♦❣❡t❤❡r
❢ ❂ ❝✯✯✹ ★ r❛✐s❡ ♥✉♠❜❡r t♦ ❛ ♣♦✇❡r ✭✉s❡ ✯✯✱ ♥♦t ❫✮

t In Python 2.x the single Performing an operation on two integers usually yields another integer. This can
slash between two integer pose an ambiguity for division where the result is rarely an exact integer. Using the
variables performs integer regular division operator (as in the line defining ❞ above) for two integers yields
division. If you are using
a float, whereas the double slash (used in the line defining ✐) performs integer
this older version of Python,
you should be sure to use
division. Look at the variable values in the variable explorer and compare them
floats when you want regu- to your code to convince yourself that you understand the distinction between
lar division. these two types of division.

1.6 Float variables


Most calculations in physics should be performed using floating point numbers,
❛❜s✭①✮ Find the absolute called floats in Python. Float variables are created and assigned in one of two
value of x ways. The first way is to simply include a decimal point in the number, like this
❞✐✈♠♦❞✭①✱②✮ Returns the quotient ❛ ❂ ✷✵✳
and remainder when
using long division. You can also cast an integer variable to a float variable using the ❢❧♦❛t command
① ✪ ② Return the remain- ❛ ❂ ✷✵
der of xy ❜ ❂ ❢❧♦❛t✭❛✮
❢❧♦❛t✭①✮ convert ① to a float. When a float and an integer are used in the same calculation, like this
✐♥t✭①✮ convert ① to an inte- ❛ ❂ ✵✳✶
ger. ❜ ❂ ✸ ✯ ❛ ★■♥t❡❣❡r ♠✉❧t✐♣❧✐❡❞ ❜② ❛ ❢❧♦❛t r❡s✉❧ts ✐♥ ❛ ❢❧♦❛t✳
r♦✉♥❞✭①✮ Round the number the result is always a float. Only when all of the numbers used in a calculation
① using standard
are integers will the result be an integer. Floats can be entered using scientific
rounding rules
notation like this

Table 1.1 A sampling of built-in ② ❂ ✶✳✷✸❡✶✺


functions commonly used with
integers and floats.
1.7 Functions and Help
Table 1.1 shows some common housekeeping functions that you can use with
float variables. Practice using one of these functions in your code. Then place
your cursor on the function name in your code and press Ctrl-I (think “I is for
information) to display detailed information about this function in the help panel.
You can use this method for getting details of calling conventions and function
usage for all of the functions we use in this class.
1.8 Boolean variables 5

1.8 Boolean variables


Boolean variables store one of two possible values: ❚r✉❡ or ❋❛❧s❡. A boolean
variable is created and assigned similar to the other variables you’ve studied so
far
q ❂ ❚r✉❡
Boolean variables will be useful when we use loops and logical statements. len(c) Get the number of
characters in the
string ❝
1.9 String Variables
❛✳❝♦✉♥t✭❜✮ Count the number
of occurrences of
String variables contain a sequence of characters, and can be created and assigned
string ❜ in string ❛
using quotes, like this
s❂✬❚❤✐s ✐s ❛ str✐♥❣✬ ❛✳❧♦✇❡r✭✮ Convert upper case
letters to lower case
You may also enclose the characters in double quotes. This syntax is convenient
when there are single quotes in your string: ❛❬①❪ Access element ① in
string ❛
t❂✧❉♦♥✬t ✇♦rr②✧
❛❬①✿②✿③❪ Slice a string, start-
Some Python functions require options to be passed to them as strings. Make sure ing at element ①,
you enclose them in quotes, as shown above. Some commonly used functions for ending at element ②,
strings are shown in Table 1.2 with a step size of ③

❛ ✰ ❜ Concatenate strings
1.10 Formatting Printed Values ❛ and ❜.

Table 1.2 A sampling of “house-


The ♣r✐♥t command will take pretty much any variable and dump it to screen in keeping” functions for strings.
a format of Python’s choosing. However, there are times when you’ll want to be
more careful about the formatting of your print statements. For example:
❛ ❂ ✷✷ ④⑥ Use the default for-
❜ ❂ ✸✳✺ mat for the data type
♣r✐♥t✭✧■ ❛♠ ④✿❞⑥ ②❡❛rs ♦❧❞ ❛♥❞ ♠② ●P❆ ✐s✿ ④✿✺✳✷❢⑥✧✳❢♦r♠❛t✭❛✱ ❜✮✮
④✿✹❞⑥ Display integer with
★❚❤✐s st②❧❡ ❛❧s♦ ✇♦r❦s 4 spaces
❥♦❡❴str✐♥❣❂✧▼② ●P❆ ✐s ④✿✺✳✷❢⑥ ❛♥❞ ■ ❛♠ ④✿❞⑥ ②❡❛rs ♦❧❞✳✧
④✿✳✹❢⑥ Display float with 4
♣r✐♥t✭❥♦❡❴str✐♥❣✳❢♦r♠❛t✭❜✱❛✮✮
numbers after the
Notice the structure of this formatted print statement: A string followed by the ✳ decimal
operator and the ❢♦r♠❛t✭✮ method. Those of you familiar with object-oriented
④✿✽✳✹❢⑥ Display float with at
coding will notice that this is an example of Python’s fully object-oriented struc- least 8 total spaces
ture. The variables to be printed are provided as arguments to the ❢♦r♠❛t method and 4 numbers after
and are inserted into the string sequentially where curly braces (④⑥) are found. the decimal
The characters inside of the curly braces are format codes that indicates how you
④✿✶✳✷❡⑥ Scientific notation
would like the variable formatted when it is printed. The ✿❞ indicates an integer with 2 digits after
variable and ✿❢ indicates a float. The ✺✳✷ in the float formatting indicates that the decimal
I’d like the number to be displayed with at least 5 digits and 2 numbers after the
decimal. See Table 1.3 for format examples. Table 1.3 Formatting strings avail-
able when printing.
6 Chapter 1 Numpy, Scipy, and Plotting

1.11 Functions and Libraries (Numpy)


The syntax for calling Python functions is fairly standard: you type the name of
the function and put parentheses ✭✮ around the arguments, like this
① ❂ ✸✳✶✹
② ❂ r♦✉♥❞✭①✮

If the function requires more than one argument or returns more than one value,
you separate the arguments and outputs with commas, like this
① ❂ ✸✳✶✹
② ❂ ✷
❜✱❝ ❂ ❞✐✈♠♦❞✭①✱②✮

Pause a moment after executing this code to compare the values of ❜ and ❝ with
the code above, and convince yourself that you understand how function calls
work with multiple arguments and outputs in Python.
Python contains a set of standard functions, called native functions, that are
always ready to go whenever you run Python. All the functions we’ve used so
far fall into this category. While useful, these native functions are inadequate
for scientific computing. However, user communities have created extensive
collections of functions called libraries that you can import into Python to extend
its native capabilities.
For example, Python doesn’t natively include the sine and cosine functions.
However, virtually any mathematical function that you will need to perform a
scientific calculation can be found in a library called NumPy (say “num pie”, not
something that rhymes with grumpy). To use this library, we add an ✐♠♣♦rt
s✐♥✭①✮ statement to the beginning of our program, and then reference the functions in
❝♦s✭①✮
t❛♥✭①✮
this library like this
❛r❝s✐♥✭①✮ ✐♠♣♦rt ♥✉♠♣②
❛r❝❝♦s✭①✮
❛r❝t❛♥✭①✮
① ❂ ♥✉♠♣②✳♣✐ ★ ●❡t t❤❡ ✈❛❧✉❡ ♦❢ ♣✐
s✐♥❤✭①✮
❝♦s❤✭①✮ ② ❂ ♥✉♠♣②✳s✐♥✭①✮ ★ ❋✐♥❞ t❤❡ s✐♥❡ ♦❢ ♣✐ r❛❞✐❛♥s
t❛♥❤✭①✮ ③ ❂ ♥✉♠♣②✳sqrt✭①✮ ★ ❚❛❦❡ t❤❡ sq✉❛r❡ r♦♦t ♦❢ ♣✐
s✐❣♥✭①✮
❡①♣✭①✮ After importing the library, the code “♥✉♠♣②✳” before a function tells Python to
sqrt✭①✮ look in the NumPy library to find the function rather than in the native functions.
❧♦❣✭①✮ If you just type
❧♦❣✶✵✭①✮
❧♦❣✷✭①✮ sqrt✭①✮

Table 1.4 A very small sampling of Python will look for a native function named sqrt and will give you an error.
functions belonging to the ♥✉♠♣② A library can be imported and then referenced by a different name like this:
library.
✐♠♣♦rt ♥✉♠♣② ❛s ♥♣

① ❂ ♥♣✳sqrt✭✺✳✷✮ ★ ❚❛❦❡ t❤❡ sq✉❛r❡ r♦♦t ♦❢ ✺✳✷


② ❂ ♥♣✳♣✐ ★ ●❡t t❤❡ ✈❛❧✉❡ ♦❢ ♣✐
③ ❂ ♥♣✳s✐♥✭✸✹✮ ★ ❋✐♥❞ t❤❡ s✐♥❡ ♦❢ ✸✹ r❛❞✐❛♥s
1.12 Numpy Arrays 7

This syntax tells Python “I’m going to call the ♥✉♠♣② library ♥♣.” We recommend
that you use this syntax for the NumPy unless there is some compelling reason to
do otherwise. It is so common to do this, that in this manual we will usually omit
writing the code

✐♠♣♦rt ♥✉♠♣② ❛s ♥♣

at the beginning of each example and just assume that you’ll include it whenever
you see functions with the “♥♣✳” prefix.
Virtually any mathematical function that you will need to perform a scientific
calculation can be found in the library NumPy or in another common library
called SciPy (say “sigh pie”, not “skippy”). These two libraries are designed to work ❛✐r②✭③✮ Airy function
together. Here is an example showing how to use the J 0 Bessel function:
❥✵✭③✮ 0th order Bessel
✐♠♣♦rt ♥✉♠♣② ❛s ♥♣ function of 1st kind
✐♠♣♦rt s❝✐♣②✳s♣❡❝✐❛❧ ❛s s♣s
❥✶✭③✮ 1st order Bessel
❛ ❂ ✺✳✺ function of 1st kind
❜ ❂ ✻✳✷
❝ ❂ ♥♣✳♣✐✴✷ ❥✈✭✈✱③✮ Bessel function of
1st kind, order ✈
❞ ❂ ❛ ✯ ♥♣✳s✐♥✭❜ ✯ ❝✮
❡ ❂ ❛ ✯ s♣s✳❥✵✭✸✳✺ ✯ ♥♣✳♣✐✴✹✮ ②✈✭✈✱③✮ Bessel function of
2nd kind, order ✈
If ♥✉♠♣② doesn’t have a mathematical function you need, then s❝✐♣②✳s♣❡❝✐❛❧
probably has it. Table 1.5 provides a small sampling of its functions. See SciPy’s ❦✈✭♥✱③✮ Modified Bessel
online help for a more extensive listing. function of 2nd
kind of integer
order n
1.12 Numpy Arrays
✐✈✭✈✱③✮ Modified Bessel
function of 1st kind
In scientific computing we often do calculations involving large data sets. Say you
of real order v
have a large set of numbers, x i and you want to calculate the summation
❤❛♥❦❡❧✶✭✈✱③✮ Hankel function of
N
1st kind of real or-
(x i − 5)3 .
X
(1.1) der v
i =1

❤❛♥❦❡❧✷✭✈✱③✮ Hankel function of


You could use loops to calculate each term in this sum one-by-one, and then add
2nd kind of real or-
them up to compute the final sum. However, the Numpy library provides a much der v
slicker method for making these kinds of calculation using something called a
NumPy array. For example, if ① were a Numpy array containing all of the x i values, Table 1.5 A very small sampling
the code to evaluate the sum in Eq. (2.1) is simply: of functions belonging to the
s❝✐♣②✳s♣❡❝✐❛❧ library.
s❂s✉♠✭✭①✲✺✮✯✯✸✮

This code subtracts 5 from each element in the array, cubes the result for each
element, and then sums the resulting elements all without a loop in sight. Let’s
explore the details of how to do calculation using Numpy arrays.
8 Chapter 1 Numpy, Scipy, and Plotting

Array Creation
Our first task is to create a NumPy array. Here you have several options. You can
enter small arrays by providing a list of numbers to the NumPy ❛rr❛② function,
like this:

❛ ❂ ♥♣✳❛rr❛②✭❬✶✱✷✱✸✱✹✱✺✱✻✱✼✱✽✱✾✱✶✵❪✮

Another common method for creating arrays is to use the function ❛r❛♥❣❡ (think
the two words “a range” not the one word “arrange” so you don’t misspell this
function). This function creates an array of evenly spaced values from a starting
value, and ending value, and a step size, like this:

❜ ❂ ♥♣✳❛r❛♥❣❡✭✵✱✶✵✱✳✶✮

This code creates the following array:


❧♦❣s♣❛❝❡ Returns numbers
evenly spaced on a ❬✵✱✳✶✱✳✷✱✳✸✱✳✹✱✳✺✱✳✻✳✳✳✳ ✾✳✺✱✾✳✻✱✾✳✼✱✾✳✽✱✾✳✾❪
log scale. Same argu-
ments as ❧✐♥s♣❛❝❡
Notice that this array does not include the value at the end of the range (i.e. 10).
❡♠♣t② Returns an empty ar- Also, for those of you coming from a Matlab background, notice that the step size
ray with the speci- (0.1 in this case) comes third, not between the two limits as is done in Matlab.
fied shape The ❧✐♥s♣❛❝❡ function creates an array by specifying the starting value, end-
ing value, and the number of elements that the array should contain. For example:
③❡r♦s Returns an array of
zeros with the spec- ① ❂ ♥♣✳❧✐♥s♣❛❝❡✭✵✱✶✵✱✶✵✮
ified shape
This will create an array that looks like this:
♦♥❡s Returns an array of
ones with the speci- ❬✵✱✶✳✶✶✶✱✷✳✷✷✷✱✸✳✸✸✸✱✹✳✹✹✹✱✺✳✺✺✺✱✻✳✻✻✻✱✼✳✼✼✼✱✽✳✽✽✽✱✶✵❪
fied shape.
When you use the ❧✐♥s♣❛❝❡ function, you aren’t specifying a step size. You can
③❡r♦s❴❧✐❦❡ Returns an array of
ask the ❧✐♥s♣❛❝❡ command to tell you what step size results from the array that
zeros with the same
shape as the pro- it created by adding r❡tst❡♣❂❚r✉❡ as an argument to the function, like this:
vided array.
①✱❞① ❂ ♥♣✳❧✐♥s♣❛❝❡✭✵✱✶✵✱✶✵✱r❡tst❡♣ ❂ ❚r✉❡✮
❢r♦♠❢✐❧❡ Read in a file and cre-
ate an array from the Note that since ❧✐♥s♣❛❝❡ is now returning two values (the array and the step
data. size), we need two variables on the left hand side of the equals sign. Table 1.6
gives several other options for creating NumPy arrays.
❝♦♣② Make a copy of an-
other array.
Math with Arrays

Table 1.6 A sampling of array- Once a NumPy array object is created, a whole host of mathematical operations
building functions in numpy. The become available—you can square the array and Python knows that you want to
arguments to the functions has square each element, you can add two arrays together and Python knows that you
been omitted to maintain brevity. want to add the individual elements of the arrays, etc. Here are some examples:
See online documentation for
further details.
1.12 Numpy Arrays 9

① ❂ ♥♣✳❛rr❛②✭❬✷✱✸✱✺✳✷✱✷✱✻✳✼✱✸❪✮ ★ ❈r❡❛t❡ t❤❡ ❛rr❛② ①


② ❂ ♥♣✳❛rr❛②✭❬✹✱✽✱✾✳✽✱✷✳✶✱✽✳✷✱✹✳✺❪✮ ★ ❈r❡❛t❡ t❤❡ ❛rr❛② ②

❝ ❂ ①✯✯✷ ★ ❙q✉❛r❡ t❤❡ ❡❧❡♠❡♥ts ♦❢ ①


❞ ❂ ① ✰ ✸ ★ ❆❞❞ ✸ t♦ ❡✈❡r② ❡❧❡♠❡♥t ♦❢ ①
❡ ❂ ① ✯ ✺ ★ ▼✉❧t✐♣② ❡✈❡r② ❡❧❡♠❡♥t ♦❢ ① ❜② ✺
❢ ❂ ① ✰ ② ★ ❆❞❞ t❤❡ ❡❧❡♠❡♥ts ♦❢ ① t♦ t❤❡ ❡❧❡♠❡♥ts ②
❣ ❂ ① ✯ ② ★ ▼✉❧t✐♣❧② t❤❡ ❡❧❡♠❡♥ts ♦❢ ① ❜② t❤❡ ❡❧❡♠❡♥ts ♦❢ ②

In most respects, math with Numpy arrays behaves like the “dotted” operators
with Matlab matrices, where the operations are performed on corresponding
elements. However, NumPy arrays are objects, so assigning one array to another,
like this

① ❂ ♥♣✳❛rr❛②✭❬✷✱✸✱✺✳✷✱✷✱✻✳✼✱✸❪✮
② ❂ ①

does not copy the values of ① into a new variable ②. Instead, it creates a new
pointer to the existing object ①, so that ① and ② now refer to the same object. Try
changing a value of ② and note that it also changes the value in ①. To make a copy
of an array, do this

① ❂ ♥♣✳❛rr❛②✭❬✷✱✸✱✺✳✷✱✷✱✻✳✼✱✸❪✮
② ❂ ♥♣✳❝♦♣②✭①✮

Switch the values in ① and ② and notice that they are now independent variables.
This array copy business is important and often misunderstand. This results
in frustrated students when they try using the wrong syntax. You should proba-
bly go back and re-read the last paragraph and make sure you understand the
distinctions to save yourself some frustration.

Functions of Arrays
Mathematical functions like sin(x) and sinh(x) from the NumPy and SciPy li-
braries can accept arrays as their arguments and the output will be an array of
function values. However, functions from other libraries, such as the ♠❛t❤ library,
are not designed to work on arrays. Here is an example of this issue:

✐♠♣♦rt ♥✉♠♣② ❛s ♥♣
✐♠♣♦rt ♠❛t❤
① ❂ ♥♣✳❛rr❛②✭❬✷✱✸✱✺✳✷✱✷✱✻✳✼❪✮
❝ ❂ ♥♣✳s✐♥✭①✮ ★ ❲♦r❦s ❥✉st ❢✐♥❡✱ r❡t✉r♥✐♥❣ ❛rr❛② ♦❢ ♥✉♠❜❡rs✳
❞ ❂ ♠❛t❤✳s✐♥✭①✮ ★ ❘❡t✉r♥s ❛♥ ❡rr♦r✳

The ♠❛t❤ library is much less capable than ♥✉♠♣②, so we don’t recommend using
it for scientific coding. We just introduced it here to emphasize that NumPy arrays
usually need to be used with NumPy functions.
10 Chapter 1 Numpy, Scipy, and Plotting

Accessing Elements of Numpy Arrays


You can access individual array elements in a NumPy array using square brackets
to index the elements like this

❛ ❂ ♥♣✳❛rr❛②✭❬✶✱✷✱✸✱✹✱✺✱✻✱✼✱✽✱✾✱✶✵❪✮
① ❂ ❛❬✶❪

Look carefully at the value of ① after running this code, and convince yourself that
Python array indexes are zero-based. That is, the first element has index 0, the
second element has index 1, and so forth.
You can extract a contiguous range of values using the colon command in
square brackets like this

❜ ❂ ❛❬✶✿✹❪
❝ ❂ ❛❬✵✿✻✿✷❪

Note that there can be three numbers inside the brackets, each separated by the
✿ symbol, like this ❬①✿②✿③❪. The extracted elements start at element ①, end just
before element ② (i.e. the element at ② is not in the range), and steps in increments
of ③. Note that the last number is optional, and if omitting a default value of 1 is
used for the step size. Python uses zero-based indexing, so ❛❬✶✿✹❪ starts at the
second element, not the first.
You can also use negative indexes in the colon command to count from the
end of the array toward the beginning:

❜ ❂ ❛❬✲✶❪
❝ ❂ ❛❬✶✿✲✷❪

The index ✲✶ refers to the last element, index ✲✷ refers to the second to last
element, etc. You can also omit one of the endpoint arguments to go all the way
to the beginning or end of the array, like this:

❜ ❂ ❛❬✶✿❪
❝ ❂ ❛❬✿✸❪

1.13 Making x-y Plots


Plots of x vs. y can be made with a library called ♠❛t♣❧♦t❧✐❜. This library creates
plots using a syntax essentially the same as the plotting functions in Matlab using
NumPy arrays as data inputs. Here is an example of the basic syntax:
t Spyder uses IPython for its
console which automati- ✐♠♣♦rt ♠❛t♣❧♦t❧✐❜✳♣②♣❧♦t ❛s ♣❧t
cally shows plots. For other ✐♠♣♦rt ♥✉♠♣② ❛s ♥♣
consoles, you’ll need to add ① ❂ ♥♣✳❛r❛♥❣❡✭✵✱✶✵✱✵✳✵✶✮
the command ♣❧t✳s❤♦✇✭✮ ② ❂ ①✯✯✷
after making a plot to dis-
play it on the screen. ♣❧t✳❢✐❣✉r❡✭✶✮
♣❧t✳♣❧♦t✭①✱②✮
1.14 Customizing the IDE 11

If you want to see the actual data points being plotted, you can add the string
✬r♦✬ inside of the plot command
♣❧t✳♣❧♦t✭①✱②✱✬r♦✬✮

The ✬r✬ means make the data points red and the ✬♦✬ means plot circle markers.
All of the usual plot commands from Matlab work about the way you’d expect.
For instance, here is an example of overlaying two graphs

✐♠♣♦rt ♠❛t♣❧♦t❧✐❜✳♣②♣❧♦t ❛s ♣❧t


✐♠♣♦rt ♥✉♠♣② ❛s ♥♣

① ❂ ♥♣✳❧✐♥s♣❛❝❡✭✵✱✷✳✯♥♣✳♣✐✱✶✵✵✮
②✶ ❂ ♥♣✳s✐♥✭✷✯①✮
②✷ ❂ ♥♣✳❝♦s✭✸✯①✮

♣❧t✳❢✐❣✉r❡✭✶✮
♣❧t✳♣❧♦t✭①✱②✶✱✬r✳✬✱①✱②✷✱✬❜✬✮
♣❧t✳❧❡❣❡♥❞✭❬✬❙✐♥❡ ♦❢ ①✬✱✬❈♦s✐♥❡ ♦❢ ①✬❪✮
♣❧t✳①❧❛❜❡❧✭✬①✬✮
♣❧t✳t✐t❧❡✭✬❚✇♦ ❚r✐❣ ❋✉♥❝t✐♦♥s✬✮

♣❧t✳❢✐❣✉r❡✭✷✮
♣❧t✳♣❧♦t✭②✶✱②✷✮
♣❧t✳t✐t❧❡✭✬❙♦♠❡t❤✐♥❣ ❋❛♥❝②✬✮

1.14 Customizing the IDE


The Spyder development environment can be customized to suit your preferences.
We recommend at least the following changes, and you can also look around at
some of the other options while making these changes.

1. By default plots are displayed inline in the console. To have them pop
out in their own window go to the Tools menu in Spyder and select Prefer-
ences → IPython Console → Graphics Tab and set the Graphics backend
to “Automatic.” The popup windows will allow you to zoom in on different
parts of the graph. The separate window will also allow us to make simple
animations by repeatedly redrawing plots in the same window. If you don’t
make this change, your animations will scroll by as separate plots in the
console window rather than displaying on the same axis.

2. By default, all the variables that you define by direct interaction with the
console and during the execution of your code remain in memory and avail-
able for subsequent use, both in the console and subsequent executions
of programs. Sometimes this can be convenient, but it can also cause de-
bugging problems. For example, if you define a variable using the console
and then write a program that depends on that variable, then the mode
of execution of your program depends on what you’ve manually entered
12 Chapter 1 Numpy, Scipy, and Plotting

in the console. When learning to program, we recommend that you have


Spyder clear all variables before executing a program. To do this go to the
Tools menu in Spyder and select Preferences → Run and check the “Remove
all variables before execution” option.
Chapter 2
Lists, Loops, Logic, and 2D Arrays

2.1 Lists
You’ll encounter lists quite a bit in Python. In fact we already used some in the ❛❬①❪ Access element ①
in list ❛
previous chapter without telling you. Lists are ordered collections of values. To
❛❬①✿②✿③❪ Extract a slice of
create a list, put the elements inside of square brackets like this: list ❛
❛✳❛♣♣❡♥❞✭①✮ Append ① to list ❛
① ❂ ❬✺✳✻✱✷✳✶✱✸✳✹✱✷✳✾❪
❛✳♣♦♣✭✮ Remove the last el-
ement of list ❛.
You can make a list of any variable type. Here is a list of strings:
❧❡♥✭❛✮ Find the number
❛ ❂ ❬✬❡❧❡❝tr♦♥✬✱✬♣r♦t♦♥✬✱✬♥❡✉tr♦♥✬❪ of elements in ❛
❛✳✐♥s❡rt✭①✱②✮ Insert ② at location
List elements don’t need to be the same data type, so this list is perfectly valid ① in list ❛
❛✳s♦rt✭✮ Sort list ❛ from
❛ ❂ ❬✬❇❡♥✬✱✾✵✱✬❈❤❛❞✬✱✼✺✱✬❆♥❞r❡✇✬✱✷✷❪ least to greatest.
❢✐❧t❡r✭❢✱①✮ Filter list ① using
You can even define a list of lists: the criteria func-
tion ❢(see lambda
❛ ❂ ❬❬✹✱✸✱✷❪✱❬✶✱✷✳✺✱✾❪✱❬✹✳✷✱✷✳✾✱✶✵✳✺❪✱❬✸✾✳✹✱✶✳✹❪✱❬✷✳✼✱✾✽✱✹✷✱✶✻✳✷❪❪ functions).
❛✳r❡✈❡rs❡✭✮ Reverse the order
When looking at the numerical lists above, you might be tempted to think of
of list ❛.
lists as mathematical matrices. Don’t. Lists are not really designed for mathemat- ❛✳✐♥❞❡①✭①✮ Find the index
ics. To convince yourself of this, add the statement where element x
resides.
❛❬✶❪❬✷❪ ❂ ✬❣❡♦r❣❡✬ ❛ ✰ ❜ Join list ❛ to list ❜
to form one list.
after the list of lists above and then examine ❛. You can’t calculate on elements
that aren’t numbers! As another example, execute this code ♠❛①✭❛✮ Find the largest el-
ement of ❛
✐♠♣♦rt ♥✉♠♣② ❛s ♥♣
① ❂ ♥♣✳❛rr❛②✭❬✶✱✷✱✸❪✮ ★ ① ✐s ❛ ◆✉♠P② ❛rr❛② ♠✐♥✭❛✮ Find the smallest
♣r✐♥t✭①✰①✮ ★ ❛❞❞✐♥❣ t✇♦ ◆✉♠P② ❛rr❛②s ❛❞❞s t❤❡ ✈❛❧✉❡s element of ❛

② ❂ ❬✶✱✷✱✸❪ ★ ② ✐s ❛ P②t❤♦♥ ❧✐st s✉♠✭❛✮ Returns the sum of


♣r✐♥t✭②✰②✮ ★ ❛❞❞✐♥❣ ❧✐sts ❝♦♥❝❛t❡♥❛t❡s t❤❡ t✇♦ ❧✐sts the elements of ❛

Study the output from this code and convince yourself that NumPy arrays are the
right object for doing math, not lists. However, lists are otherwise quite useful Table 2.1 A sampling of “house-
keeping” functions for lists.
in Python. Table 2.1 gives a list of common list functions. Note that lists are
objects with methods (e.g. ❛✳s♦rt✭✮), but can also be used as arguments to
other functions (e.g. ❧❡♥✭❛✮. Like many things in Python, the reasons for the
different syntaxes are known only to those who developed Python. For example,
why does ❧❡♥✭❛✮ work, but ❛✳❧❡♥✭✮ return an error? The organic nature of the
development of Python syntax results in some inconsistencies in syntax that just
need to be learned.

13
14 Chapter 2 Lists, Loops, Logic, and 2D Arrays

2.2 The r❛♥❣❡ Function


Python’s r❛♥❣❡ function represents a sequence of integer values that behaves a
lot like a list. The syntax of this function is like this

❛ ❂ r❛♥❣❡✭✶✵✱✷✵✱✷✮

This statement represents a sequence of integers that starts at 10, ends at 18,
and steps in increments of 2. The r❛♥❣❡ function does not include the item at
the endpoint of the range. In Python 2.x, the r❛♥❣❡ function returned an actual
list object, but in Python 3.x (which we are using) it returns an object called an
iterator. Rather than store a huge list of numbers, an iterator just stores the rule
for generating the number at any index. So, if you print the range variable

♣r✐♥t✭❛✮

Python will just tell you that ❛ represents a range, but if you execute this code

❛❬✷❪

you can get an actual value.


The r❛♥❣❡ function can also be called with 1 or 2 arguments and default
values will be assigned to the missing ones.

❜ ❂ r❛♥❣❡✭✸✱✾✮ ★ st❛rts ❛t ✸✱ ❡♥❞s ❛t ✽✱ st❡♣s ♦❢ ✶ ✭❞❡❢❛✉❧t✮


❝ ❂ r❛♥❣❡✭✶✵✮ ★ st❛rts ❛t ✵ ✭❞❡❢❛✉❧t✮✱ ❡♥❞s ❛t ✾✱ st❡♣s ♦❢ ✶ ✭❞❡❢❛✉❧t✮

2.3 For Loops and Shorthand Assignments


The primary use for the r❛♥❣❡ function in writing ❢♦r loops. A ❢♦r loop iterates
over each element in a list or range. Here is a ❢♦r loop used to sum a list of values
t Usually you would just use
a s✉♠ function, but we are s ❂ ✵
learning about loops here. ❢♦r ① ✐♥ ❬✸✱✹✷✱✶✱✾✳✾❪✿
s ❂ s ✰ ①
♣r✐♥t✭s✮

This code iterates over the list ❬✸✱✹✷✱✶✱✾✳✾❪, assigning the variable ① each value
in the list, one by one, until it reaches the end of the list. Notice the required colon
at the end of the ❢♦r statement that marks the beginning of the loop, and also that
there is no code indicating the end of the ❢♦r loop. Python uses indentation to
denote the group of code that will be executed during each iteration. To see this,
indent the ♣r✐♥t✭s✮ statement to the same level as the statement above it and
execute the code. Note that the ♣r✐♥t function now executes on each iteration of
the loop instead of just displaying the final value of s.
You can also iterate over the values from the r❛♥❣❡ function, like this

❢♦r ② ✐♥ r❛♥❣❡✭✺✱✺✵✱✸✮✿
♣r✐♥t✭②✮
2.4 Logical Statements 15

The r❛♥❣❡ function only produces integers, so the most common use case is to
use it with a ❢♦r loop to index a separate array, like this

① ❂ ♥♣✳❛r❛♥❣❡✭✺✱✶✵✱✳✶✮

❢♦r ♥ ✐♥ r❛♥❣❡✭❧❡♥✭①✮✮✿
♣r✐♥t✭①❬♥❪✮

You can also iterate directly over the values of an array, like this:

① ❂ ♥♣✳❛r❛♥❣❡✭✺✱✶✵✱✳✶✮

❢♦r ② ✐♥ ①✿
♣r✐♥t✭②✮

To practice ❢♦r loops, let’s build a loop to calculate the sum

1000
X 1
n=1 n2

s ❂ ✵
❢♦r ♥ ✐♥ r❛♥❣❡✭✶✱✶✵✵✶✮✿
s ✰❂ ✶✴♥✯✯✷
♣r✐♥t✭s✮
Operation Shorthand
The code s ✰❂ ✶✴♥✯✯✷ is equivalent to s ❂ s ✰ ✶✴♥✯✯✷, but runs a little faster ❛ ❂ ❛ ✰ ✶ ❛ ✰❂ ✶
❛ ❂ ❛ ✲ ✷ ❛ ✲❂ ✷
and is a little bit easier to read (once you get used to it). See Table 2.2 for more ❛ ❂ ✺✯❛ ❛ ✯❂ ✺
shorthand notations. Here’s another example of a loop used to calculate the value ❛ ❂ ❛✴❝ ❛ ✴❂ ❝
of p = 20! (20 factorial) using another shorthand notation ❛ ❂ ❛ ✪ ✶✵ ❛ ✪❂ ✶✵
❛ ❂ ❛✯✯✸ ❛ ✯✯❂ ✸
♣ ❂ ✶ ❛ ❂ ❛ ✴✴ ✶✷ ❛ ✴✴❂ ✶✷
❢♦r ♥ ✐♥ r❛♥❣❡✭✶✱✷✶✮✿
♣ ✯❂ ♥ ★ ▼✉❧t✐♣❧② ♣ ❜② ♥ Table 2.2 A list of shorthand vari-
♣r✐♥t✭♣✮ able reassignment notation.

Remember that the range function starts at the first argument (i.e. 1), and goes
up to, but not including the second argument, so our product will only go up to
n = 20.

2.4 Logical Statements


Often we only want to run a section of code only when some condition is satisfied.
This requires the use of logic. The simplest logic is the ✐❢❭❡❧✐❢❭❡❧s❡ statement,
which works like this:

❛ ❂ ✶
❜ ❂ ✸
✐❢ ❛ ❃ ✵✿
❝ ❂ ✶
❡❧s❡✿
16 Chapter 2 Lists, Loops, Logic, and 2D Arrays

❝ ❂ ✵

✐❢ ❛ ❃❂ ✵ ♦r ❜ ❃❂ ✵✿ ★ ■❢ ❝♦♥❞✐t✐♦♥ ✶ ♠❡t
❝ ❂ ❛ ✰ ❜
❡❧✐❢ ❛ ❃ ✵ ❛♥❞ ❜ ❃❂ ✵✿ ★ ■❢ ❝♦♥❞✐t✐♦♥ ✷ ♠❡t
❝ ❂ ❛ ✲ ❜
❡❧s❡✿ ★ ■❢ ♥❡✐t❤❡r ❝♦♥❞✐t✐♦♥ ✐s ♠❡t✳
❝ ❂ ❛ ✯ ❜

Note the locations of colons in these statements, and also note that indentation
again defines the regions of code that execute as a group. Table 2.3 lists the
standard elements for constructing logical statements.
❂❂ Equal
A word of caution about comparing Python floats is in order here. Because
❃❂ Greater than or of the way floats are represented in a computer, the number that is stored in a
equal float is often not exactly the number that you think it is. For instance, execute the
following, and study the output:
❃ Greater than
❛ ❂ ✵✳✶
❁ Less than ❜ ❂ ✸ ✯ ❛
❝ ❂ ✵✳✸
❁❂ Less than or equal ♣r✐♥t✭❜❂❂❝✮ ★ ❆r❡ t❤❡② t❤❡ s❛♠❡ ♥✉♠❜❡r❄
♣r✐♥t✭❜✮ ★ ■t s✉r❡ ❧♦♦❦s ❧✐❦❡ t❤❡② ❛r❡ t❤❡ s❛♠❡✳
✦❂ Not equal
♣r✐♥t✭❝✮ ★ ■t s✉r❡ ❧♦♦❦s ❧✐❦❡ t❤❡② ❛r❡ t❤❡ s❛♠❡✳
❛♥❞ True if both condi-
♣r✐♥t✭✧ ④✿✳✹✺❢⑥ ✧✳❢♦r♠❛t✭❜✮✮ ★❜✲✲✲ ♦✉t t♦ ✹✺ ❞❡❝✐♠❛❧ ♣❧❛❝❡s
tions joined by ❛♥❞ ♣r✐♥t✭✧ ④✿✳✹✺❢⑥ ✧✳❢♦r♠❛t✭❝✮✮ ★❝✲✲✲ ♦✉t t♦ ✹✺ ❞❡❝✐♠❛❧ ♣❧❛❝❡s
are true
This can cause problems when you are comparing two numbers that you think
♦r True if either of the should be equal but actually aren’t equal in the computer. The take home here
conditions joined by is that comparing two floats to see if they are equal is a bad idea. A better way
♦r are true to check to see if two floats are equal (or close enough that we can say they are
♥♦t True if the following
equal) is to check if the absolute value of their difference is very small, like this:
condition is false.
❛ ❂ ✵✳✶
❜ ❂ ✸ ✯ ❛
Table 2.3 Python’s logic elements. ❝ ❂ ✵✳✸
♣r✐♥t✭❛❜s✭❜ ✲ ❝✮ ❁ ✶❡✲✶✵✮

2.5 While Loops


A ✇❤✐❧❡ loop iterates until a certain condition is met. This loop is a good choice
when you don’t know beforehand exactly how many iterations of the loop will be
executed but rather what condition you want to be met before finishing. As an
example, let’s compute the sum
X 1
(2.1)
n2
by looping until the terms become smaller than 1 × 10−10 .
t❡r♠ ❂ ✶ ★ ▲♦❛❞ t❤❡ ❢✐rst t❡r♠ ✐♥ t❤❡ s✉♠
s ❂ t❡r♠ ★ ■♥✐t✐❛❧✐③❡ t❤❡ s✉♠
2.5 While Loops 17

♥ ❂ ✶ ★ ❙❡t ❛ ❝♦✉♥t❡r
✇❤✐❧❡ t❡r♠ ❃ ✶❡✲✶✵✿ ★ ▲♦♦♣ ✇❤✐❧❡ t❡r♠ ✐s ❜✐❣❣❡r t❤❛♥ ✶❡✲✶✵
♥ ✰❂ ✶ ★ ❆❞❞ ✶ t♦ ♥ s♦ t❤❛t ✐t ✇✐❧❧ ❝♦✉♥t✿ ✷✱✸✱✹✱✺
t❡r♠ ❂ ✶✳✴♥✯✯✷ ★ ❈❛❧❝✉❧❛t❡ t❤❡ ♥❡①t t❡r♠ t♦ ❛❞❞
s ✰❂ t❡r♠ ★ ❆❞❞ ✶✴♥❫✷ t♦ t❤❡ r✉♥♥✐♥❣ t♦t❛❧

This loop will continue to execute until t❡r♠ is less than 10−10 . Note that indenta-
tion again defines the extent of the code that will execute each iteration. Unlike
the ❢♦r loop, you have to do your own counting in a ✇❤✐❧❡ loop. Be careful about
what value ♥ starts at and when it is incremented (♥✰❂✶). Also notice that t❡r♠
must be assigned prior to the start of the loop. If it isn’t the loop’s first logical test
will fail and the loop won’t execute at all.

The ❜r❡❛❦ statement


Sometimes ✇❤✐❧❡ loops are awkward to use because you can get stuck in an infi-
nite loop if your check condition is never true. The ❜r❡❛❦ command is designed
to help you here. When ❜r❡❛❦ is executed in a loop the script jumps to just after t If you are stuck in a loop,
the end at the bottom of the loop. The ❜r❡❛❦ command also works with ❢♦r loops. you can force your program
to stop by pressing ctrl+c or
Here is our sum loop rewritten with break
cmd+c
t❡r♠ ❂ ✶ ★ ▲♦❛❞ t❤❡ ❢✐rst t❡r♠ ✐♥ t❤❡ s✉♠
s ❂ t❡r♠ ★ ■♥✐t✐❛❧✐③❡ t❤❡ s✉♠
♥ ❂ ✶ ★ ❙❡t ❛ ❝♦✉♥t❡r
✇❤✐❧❡ t❡r♠ ❃ ✶❡✲✶✵✿ ★ ▲♦♦♣ ✇❤✐❧❡ t❡r♠ ✐s ❜✐❣❣❡r t❤❛♥ ✶❡✲✶✵
♥ ✰❂ ✶ ★ ❆❞❞ ✶ t♦ ♥ s♦ t❤❛t ✐t ✇✐❧❧ ❝♦✉♥t✿ ✷✱✸✱✹✱✺
t❡r♠ ❂ ✶✳✴♥✯✯✷ ★ ❈❛❧❝✉❧❛t❡ t❤❡ ♥❡①t t❡r♠ t♦ ❛❞❞
s ✰❂ t❡r♠ ★ ❆❞❞ ✶✴♥❫✷ t♦ t❤❡ r✉♥♥✐♥❣ t♦t❛❧
✐❢ ♥ ❃ ✶✵✵✵✿
♣r✐♥t✭✬❚❤✐s ✐s t❛❦✐♥❣ t♦♦ ❧♦♥❣✳ ■✬✬♠ ♦✉tt❛ ❤❡r❡✳✳✳✬✮
❜r❡❛❦

The ❝♦♥t✐♥✉❡ statement


Another statement that is used with loops is the ❝♦♥t✐♥✉❡ statement. When
❝♦♥t✐♥✉❡ is used, the remainder of the code for the current iteration is skipped
and the next iteration of the loop begins. If you wanted to do the sum in Eq. (2.1)
but only include those terms for which n is a multiple of 3, you could do this

t❡r♠ ❂ ✶ ★ ▲♦❛❞ t❤❡ ❢✐rst t❡r♠ ✐♥ t❤❡ s✉♠


s ❂ t❡r♠ ★ ■♥✐t✐❛❧✐③❡ t❤❡ s✉♠
♥ ❂ ✶ ★ ❙❡t ❛ ❝♦✉♥t❡r
✇❤✐❧❡ t❡r♠ ❃ ✶❡✲✶✵✿ ★ ▲♦♦♣ ✇❤✐❧❡ t❡r♠ ✐s ❜✐❣❣❡r t❤❛♥ ✶❡✲✶✵
♥ ✰❂ ✶ ★ ❆❞❞ ✶ t♦ ♥ s♦ t❤❛t ✐t ✇✐❧❧ ❝♦✉♥t✿ ✷✱✸✱✹✱✺
✐❢ ♥ ✪ ✸ ✦❂ ✵✿
❝♦♥t✐♥✉❡ ★ ❙❦✐♣ t❤❡ r❡st ♦❢ t❤❡ ❝♦❞❡✱ st❛rt t❤❡ ♥❡①t ✐t❡r❛t✐♦♥
t❡r♠ ❂ ✶✳✴♥✯✯✷ ★ ❈❛❧❝✉❧❛t❡ t❤❡ ♥❡①t t❡r♠ t♦ ❛❞❞
s ✰❂ t❡r♠ ★ ❆❞❞ ✶✴♥❫✷ t♦ t❤❡ r✉♥♥✐♥❣ t♦t❛❧
18 Chapter 2 Lists, Loops, Logic, and 2D Arrays

Now, when the value of ♥ is not a multiple of 3, the last two lines of code in the
loop will be skipped.

2.6 2D NumPy Arrays–Matrices


We introduced 1D NumPy arrays in the last chapter. The syntax for two-dimensional
arrays (matrices) builds on this foundation. Small matrices can be built by giving
the ❛rr❛② function an argument that is a list of lists, like this

❛ ❂ ♥♣✳❛rr❛②✭❬❬✶✱✷✱✸❪✱❬✹✱✺✱✻❪✱❬✼✱✽✱✾❪❪✮

which could be interpreted as this matrix:

1 2 3
 
 4 5 6  (2.2)
7 8 9

Once you have a 2D array, single elements can be extracted with this syntax:

❜ ❂ ❛❬✵✱✷❪

This code extracts the number 3, the element in the first row and third column in
the array ❛. If you wanted to slice out the following 2 × 2 sub-matrix:
µ ¶
5 6
(2.3)
8 9

you could do it like this:

❜❬✶✿✸✱✶✿✸❪ ★ ❙❧✐❝❡ ♦✉t ❛ s✉❜✲❛rr❛②

If you want all of the elements in a given dimension, use the ✿ alone with no
numbers surrounding it. For example, the following:

❜❬✿✱✶✿✸❪

would extract all of the rows on columns 1 and 2:

2 3
 
 5 6  (2.4)
8 9

This kind of slicing can’t be done with lists.

Creating Larger Matrices


You can create larger arrays using several functions from NumPy. To create an
array full of zeros, you use this syntax:

❆ ❂ ♥♣✳③❡r♦s✭✭✶✵✵✱✷✵✵✮✮
2.7 Solving a Set of Linear Equations 19

This creates an array with 100 rows and 200 columns, completely full of zeros. The
argument that you provide to the ③❡r♦s function, a set of numbers surrounded
by round parentheses, is a data type called a tuple. Tuples behave a lot like lists,
except they are immutable (i.e. after you create a tuple, you can’t change the
item values). We won’t use tuples a whole lot in computational physics, but you
should be aware of what they are since you periodically need to create them as
arguments for functions. You can also ask a NumPy array what size it is using the
array’s s❤❛♣❡ property, like this
s ❂ ❆✳s❤❛♣❡
Notice that the s❤❛♣❡ property returns a tuple.
To create an array full of ones, you use this syntax:
❇ ❂ ♥♣✳♦♥❡s✭✭✶✵✵✱✷✵✵✮✮
You can also create an identity matrix like this
■ ❂ ♥♣✳✐❞❡♥t✐t②✭✶✵✵✮
Since identity matrices must be square, it only requires one number as an argu-
ment rather than a tuple.

Math with Matrices


Once a 2D array is defined, it behaves as a matrix and you can perform all the
standard linear algebra functions with SciPy’s linear algebra module. The matrix
multiplication operator is the ❅ symbol. Here are a few examples illustrating
matrix operations:
t NumPy also has a linear al-
✐♠♣♦rt ♥✉♠♣② ❛s ♥♣
gebra module. The SciPy
✐♠♣♦rt s❝✐♣②✳❧✐♥❛❧❣ ❛s ❧❛
version can do all that
the NumPy version can,
❛ ❂ ♥♣✳❛rr❛②✭❬❬✶✱✷❪✱❬✸✱✹❪❪✮ ★ ❈r❡❛t❡ ✷ ① ✷ ♠❛tr✐①
plus it has more advanced
❜ ❂ ♥♣✳❛rr❛②✭❬❬✺✱✻❪✱❬✽✱✾❪❪✮ ★ ❈r❡❛t❡ ✷ ① ✷ ♠❛tr✐①
functions. In addition, the
❝♦❧ ❂ ♥♣✳❛rr❛②✭❬❬✸❪✱❬✹❪❪✮ ★ ❈r❡❛t❡ ✷ ① ✶ ❝♦❧✉♠♥ ✈❡❝t♦r
SciPy linear algebra pack-
age has some optimizations
❝ ❂ ❛✳❚ ★ ❚r❛♥s♣♦s❡ t❤❡ ♠❛tr✐①
to make it run faster. We
❡ ❂ ❛✳❝♦♥❥✭✮✳❚ ★ ❋✐♥❞ ❝♦♥❥✉❣❛t❡ tr❛♥s♣♦s❡ ♦❢ ♠❛tr✐①
recommend you always
❢ ❂ ❛ ❅ ❜ ★ ▼❛tr✐① ♠✉❧t✐♣❧✐❝❛t✐♦♥
use the SciPy linear algebra
❣ ❂ ❜ ❅ ❝♦❧ ★ ▼✉❧t✐♣❧② ♠❛tr✐① ❜ t♦ ❝♦❧✉♠♥ ✈❡❝t♦r
package.
❞ ❂ ❧❛✳✐♥✈✭❛✮ ★ ❋✐♥❞ ✐♥✈❡rs❡ ♦❢ ♠❛tr✐①
The ❧✐♥❛❧❣ name space within SciPy provides lots of matrix functions. Pretty
much anything you learned about in your linear algebra class is available there.

2.7 Solving a Set of Linear Equations


To illustrate the use of matrix computations, let’s solve a set of linear equations.
Here is an example of a set of two linear equations, with two unknowns:

3x + y = 9 x + 2y = 8 (2.5)
20 Chapter 2 Lists, Loops, Logic, and 2D Arrays

This problem can be represented in matrix form like this:

Ax = b (2.6)

where µ ¶
3 1
A= , (2.7)
1 2
µ ¶
9
b= , (2.8)
8
and µ ¶
x
x= . (2.9)
y
SciPy has a function called s♦❧✈❡ that will solve this problem like this

✐♠♣♦rt ♥✉♠♣② ❛s ♥♣
✐♠♣♦rt s❝✐♣②✳❧✐♥❛❧❣ ❛s ❧❛

❛ ❂ ♥♣✳❛rr❛②✭❬❬✸✱✶❪✱❬✶✱✷❪❪✮
❜ ❂ ♥♣✳❛rr❛②✭❬❬✾❪✱❬✽❪❪✮
① ❂ ❧❛✳s♦❧✈❡✭❛✱❜✮

2.8 NumPy Matrix


NumPy provides another object called a matrix that has been widely used for
linear algebra to represent matrices. The matrix object is a subclass of the NumPy
array and provides a little cleaner syntax for manipulating matrices than the array
syntax. However, as of Python 3.5, the developers of NumPy have indicated that
they plan to deprecate the usage of the matrix type, so we haven’t taught it here.
But you may still see it in existing code bases. It is essentially a wrapper around
the NumPy array object to make some linear algebra syntax cleaner. All of the
functionality of the matrix object is available with NumPy arrays with some small
syntax changes.
Chapter 3
Functions
3.1 User-defined functions
Python’s ecosystem is extremely rich, and you can usually find a pre-made library
to do common manipulations. But you will also need to write your own functions.
User-defined functions are created like this
❞❡❢ ♠②❋✉♥❝t✐♦♥✭❛✱❜✮✿
❝ ❂ ❛ ✰ ❜
❞ ❂ ✸✳✵ ✯ ❝
❢ ❂ ✺✳✵ ✯ ❞✯✯✹
r❡t✉r♥ ❢

This function performs several simple calculations and then uses the r❡t✉r♥
statement to pass the final result back out of the function. User-defined functions
must begin with the keyword ❞❡❢ followed by the function name (you can choose
it). Python does not use an end statement to signal the end of a function. Rather,
it looks for indentation to determine where the function ends, just like it did with
loops and logic.
You can integrate this function into a larger program like this
★ ❚❤❡ ❢✉♥❝t✐♦♥ ❝♦❞❡ ✐s ♥♦t ❡①❡❝✉t❡❞ ✉♥t✐❧ t❤❡ ❢✉♥❝t✐♦♥ ✐s ❝❛❧❧❡❞ ❜❡❧♦✇✳
❞❡❢ ♠②❋✉♥❝t✐♦♥✭❛✱❜✮✿
❝ ❂ ❛ ✰ ❜
❞ ❂ ✸✳✵ ✯ ❝
❢ ❂ ✺✳✵ ✯ ❞✯✯✹
r❡t✉r♥ ❢

★❚❤❡ r❡st ♦❢ t❤✐s ❝♦❞❡ ✐s ♥♦t ♣❛rt ♦❢ t❤❡ ❢✉♥❝t✐♦♥✳


r ❂ ✶✵
t ❂ ✶✺
① ❂ ♠②❋✉♥❝t✐♦♥✭r✱t✮

In this case, when the function is called, the input ❛ gets assigned the value of
10 and input ❜ gets assigned the value of 15. The result of this calculation (❢) is
passed out of the function and stored in the variable ①.
A word on local and global variables is in order here. In the example above, the
variables ❛, ❜, ❝, ❞, and ❢ are local variables. This means that these variables are
used internally by the function when it is called and then immediately forgotten.
To see what I mean, add the following ♣r✐♥t statement at then end and observe
the results
① ❂ ♠②❋✉♥❝t✐♦♥✭r✱t✮
♣r✐♥t✭❝✮

21
22 Chapter 3 Functions

The print statement just causes an error since Python does not remember that
inside the function ❝❂❛✰❜.
In contrast, the variables r,t, and r❡s✉❧t are called global variables, which
means that Python remembers these assignments from anywhere, including
inside of functions. So, technically, you could do the following:

❣ ❂ ✾✳✽ ★ ❁✲✲✲ ❣ ❞❡❢✐♥❡❞ t♦ ❜❡ ❛ ❣❧♦❜❛❧ ✈❛r✐❛❜❧❡


❞❡❢ ♠②❋✉♥❝t✐♦♥✭❛✱❜✮✿
❝ ❂ ❛ ✰ ❣ ★ ❁✲✲✲ ◆♦t✐❝❡ t❤❡ r❡❢❡r❡♥❝❡ t♦ ❣ ❤❡r❡
❞ ❂ ✸✳✵ ✯ ❝
❢ ❂ ✺✳✵ ✯ ❞✯✯✹
r❡t✉r♥ ❢
★❚❤❡ r❡st ♦❢ t❤✐s ❝♦❞❡ ✐s ♥♦t ♣❛rt ♦❢ t❤✐s ❢✉♥❝t✐♦♥✳
r ❂ ✶✵
t ❂ ✶✺
① ❂ ♠②❋✉♥❝t✐♦♥✭r✱t✮

and there would be no error. Notice that ❣ has been defined as a global variable,
and the function ♠②❋✉♥❝t✐♦♥ knows it’s value and can use it in a calculation.
Using global variables inside functions is usually considered bad practice and
can confuse those reading the code. In general, every variable used in a function
ought to be either passed in or defined inside of the function.

3.2 Importing User Defined Functions


If you write some functions that you find yourself using over and over again, or if
you’ve written so many functions for a program that it makes your program hard
to read, you can save your functions in a separate file and import them just like a
Python library.
As an example, create a blank python file and type a couple of functions to
calculate some of the parameters of projectile motion that you learned about in
Newtonian physics:

✐♠♣♦rt ♥✉♠♣② ❛s ♥♣

❞❡❢ ♠❛①❘❛♥❣❡✭✈✵✱t❤❡t❛✮✿
❘ ❂ ✈✵✯✯✷ ✯ ♥♣✳s✐♥✭✷✯t❤❡t❛✮ ✴ ✾✳✽
r❡t✉r♥ ❘

❞❡❢ ♠❛①❍❡✐❣❤t✭✈✵✱t❤❡t❛✮✿
✈② ❂ ✈✵✯♥♣✳s✐♥✭t❤❡t❛✮
❤ ❂ ✈②✯✯✷ ✴ ✭✷✯✾✳✽✮
r❡t✉r♥ ❤

Then you save the code above in a file called ♣r♦❥❡❝t✐❧❡✳♣②. Now create another
file in that same directory, and practice importing your projectlie functions using
the following four methods (just use one method at a time):
3.3 Writing Readable Code 23

✐♠♣♦rt ♥✉♠♣② ❛s ♥♣

★▼❡t❤♦❞ ★✶
✐♠♣♦rt ♣r♦❥❡❝t✐❧❡
♣r♦❥❡❝t✐❧❡✳♠❛①❘❛♥❣❡✭✶✵✱♥♣✳♣✐✴✹✮

★▼❡t❤♦❞ ★✷
❢r♦♠ ♣r♦❥❡❝t✐❧❡ ✐♠♣♦rt ♠❛①❘❛♥❣❡
♠❛①❘❛♥❣❡✭✶✵✱♥♣✳♣✐✴✹✮

★▼❡t❤♦❞ ★✸
✐♠♣♦rt ♣r♦❥❡❝t✐❧❡ ❛s ♣❢
♣❢✳♠❛①❘❛♥❣❡✭✶✵✱♥♣✳♣✐✴✹✮

★▼❡t❤♦❞ ★✹
❢r♦♠ ♣r♦❥❡❝t✐❧❡ ✐♠♣♦rt ✯
♠❛①❘❛♥❣❡✭✶✵✱♥♣✳♣✐✴✹✮
Using these methods, you can organize your functions into neatly divided units
that you can reuse in multiple programs. By default Spyder doesn’t give you great
hints about user-defined functions. You can change this by going to Tools→
Preferences→Help, and clicking the boxes under “Automatic connections.”
It is possible to save your user-created libraries in a different folder, and then
map to them during your import, or even make your functions available to any
program using Python on your computer. When you are ready to work on larger
projects where these techniques are important, you can learn about modules and
default search paths online. However, to keep things simple in this course, just
keep your files together in the same folder.

3.3 Writing Readable Code


Comments
You should have all had several programming courses before this one, so I’ll spare
you the lecture about commenting your code. For your own sake, and for the sake
of those who may someday need to read your code, always comment your code a
little more than you think is necessary at the time you write it. Any text written
after the ★ symbol is ignored by Python as a comment:
★ ❆ ❢✉❧❧ ❧✐♥❡ ♦❢ ❝♦♠♠❡♥t✐♥❣
❊❂♠✯❝✯✯✷ ★ ❝♦♠♠❡♥ts ❛❢t❡r ❛ s❤♦rt ❧✐♥❡ ♦❢ ❝♦❞❡

Docstrings
Python also has an environment like a comment that is called a docstring, delim-
ited by a triple quote (either single or double):
✧✧✧
❚❤✐s ✐s ❛ ❞♦❝str✐♥❣✱ ✇❤✐❝❤ ❝❛♥ ❜❡ ❛✉t♦♠❛t✐❝❛❧❧② ♣❛rs❡❞ t♦ ❣❡♥❡r❛t❡
24 Chapter 3 Functions

❞♦❝✉♠❡♥t❛t✐♦♥✳ ■t ✐s ♥♦t t❤❡ s❛♠❡ ❛s ❛ ❝♦♠♠❡♥t✳


✧✧✧

Docstrings are placed immediately after the beginning of a module or a function


definition, and can be used to automatically generate documentation for your
code. You’ll see some people use them as a multi-line comment, but this is
considered bad practice. If you just want to comment your code, use the ★ symbol
in front of multiple lines. Docstrings are important when writing large code bases
to keep things well documented, but we won’t use them much in this course.

Line Continuation
To keep your lines of code from becoming too long, Python provides two ways of
continuing a logical line of code on the next physical line. The preferred method
is an implicit continuation which happens when you put a line break in your code
before closing all parenthesis, like this:

① ❂ ✭❛ ✰ ❜
✰ ❝✮

Normally you wouldn’t wrap lines of code this short, but this is just an example.
You should indent the continued line of code so that it starts right after the
unclosed opening parenthesis. You can almost always wrap lines of code this way
simply by added parentheses. You can also use the backslash to continue a line of
code, like this:

① ❂ ❛ ✰ ❜ ❭
✰ ❝

Code cells
Spyder will allow you to split your code into individual cells that can be run
separately, without executing the whole program like this

★✪✪ ❚❤✐s ✐s t❤❡ st❛rt ♦❢ ❛ ❝❡❧❧


①❂✺
②❂✻
♣r✐♥t✭①✯②✮
★✪✪ ❚❤✐s ✐s t❤❡ st❛rt ♦❢ ❛♥♦t❤❡r ❝❡❧❧
❛❂✸
❜❂✹
♣r✐♥t✭❛✴❜✮

If you place your cursor in one of the cells and press Ctrl+Enter (or push the
button to the right of the green arrow), Spyder will execute just the code in the
current cell. We generally discourage writing code using cells. The current state
of you program then depends on which cells you’ve previously executed which
can be painful to debug. However, there are times that they can be useful.
Index

Assigning values, 3

Case sensitive, 3

Data types, 3

Plotting, xy, 10

Strings, 5

25

You might also like