Introduction to Python (1)
Introduction to Python (1)
Michael J. Ware
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
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
• 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.
✶✰✶
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
① ❂ ✷✵
(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:
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 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.
❛ ✰ ❜ Concatenate strings
1.10 Formatting Printed Values ❛ and ❜.
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 ♥♣
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
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❛♥❣❡✭✵✱✶✵✱✳✶✮
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
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
❛ ❂ ♥♣✳❛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:
❜ ❂ ❛❬✶✿❪
❝ ❂ ❛❬✿✸❪
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
① ❂ ♥♣✳❧✐♥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. 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
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 ❛
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
❛ ❂ 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
❛❬✷❪
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✭②✮
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.
❛ ❂ ✶
❜ ❂ ✸
✐❢ ❛ ❃ ✵✿
❝ ❂ ✶
❡❧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✭❜ ✲ ❝✮ ❁ ✶❡✲✶✵✮
♥ ❂ ✶ ★ ❙❡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.
Now, when the value of ♥ is not a multiple of 3, the last two lines of code in the
loop will be skipped.
❛ ❂ ♥♣✳❛rr❛②✭❬❬✶✱✷✱✸❪✱❬✹✱✺✱✻❪✱❬✼✱✽✱✾❪❪✮
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
If you want all of the elements in a given dimension, use the ✿ alone with no
numbers surrounding it. For example, the following:
❜❬✿✱✶✿✸❪
2 3
5 6 (2.4)
8 9
❆ ❂ ♥♣✳③❡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.
3x + y = 9 x + 2y = 8 (2.5)
20 Chapter 2 Lists, Loops, Logic, and 2D Arrays
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♦❧✈❡✭❛✱❜✮
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♥ ❢
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:
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.
✐♠♣♦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.
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
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
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