## Contents

# Beginner's guide to Python

Take 5 minutes to get up to speed on this scientific computing language

Are you looking for an easy-to-learn programming language to help with your scientific work? Look no further than Python. We'll introduce the basic concepts you need to know to get started with this straightforward programming language and show you how to use Python for everything from running algebraic calculations to generating graphical output from your data.

## Review of scientific computing

Scientific computing involves using computers to solve scientific problems.
Specifically, it's used to solve equations. Anything from single nonlinear
equations (*root finding*) to systems of linear algebraic equations
(*numerical linear algebra*) to solving systems of nonlinear
partial differential equations (*computational physics*).

Historically, numerical algorithms to solve these problems were programmed in languages such as C/C++ and Fortran — and they still are. So, where does Python fit in? Python is great for quickly implementing and testing new (or old) algorithms, and for marshalling multiple physics codes together, which is often done at top U.S. laboratories. Python is easy, fun to learn, and quite powerful. So what are you waiting for? Let's get started!

## Download Python

Python is widely available on all
computers running the Linux or macOS operating systems. You can
even run Python on your iPad by using the Pythonista app. You can
download a version for Windows from Python.org as well. But if you're
going to do scientific computing — and even if you aren't —
I recommend you download and install Anaconda. Anaconda gives you a
full installation of Python and many of the great packages (or
*modules,* as I refer to them) for scientific
computing. It also offers easy access to the integrated development
environment Spyder.

## Python at your service

Once you have installed Anaconda, you can click the icon for the Anaconda
Navigator and start having some fun. In the bottom right window, you see a
command prompt. Simply point your mouse to the right of this
prompt and start entering Python commands. If you take the traditional
route to learning a new programming language, start by typing
`print("Hello World!")`

, then press **Return**.

You can use the command prompt to enter one or multiple commands to test code snippets quickly or generate output for your work. When it comes to more than a few lines of code, it's best to generate and save a program file separately (more on that later).

The other option, at least on Linux and macOS, is to open a terminal window
and type `Python`

at the command prompt. Doing so starts the
Python command prompt, and you can start typing commands and running
Python code. If instead you type `idle`

in the terminal window,
you get a new window featuring the Idle Python editor — convenient for
writing new Python scripts and running them by using the powerful
`F5`

command.

## What's in a name?

Now that you have Python installed and you know how to start typing commands, you can move on to doing some math and science. Computer programming to solve equations involves the use of variables and manipulation of the numbers that represent those variables. For example, define a variable in Python by typing the following command at the command prompt:

>>> x0 = 1.5 >>> x1 = 2.0

Congratulations! You just simultaneously created two new variables with
names `x0`

and `x1`

and assigned each to the values
`1.5`

and `2.0`

, respectively. To see this in
action, simply type:

>>> x0,x1

Or, you can call the `print`

function:

>>> print (x0,x1)

You don't need to declare these variables as real (floating-point numbers) or integer (whole numbers) because Python is a dynamically typed language; It figures out the variable type on the fly, based on the values assigned to it.

## Computers and algebra

You have two variables assigned to two numbers, so right away you can do some simple computer algebra with them; you can add, subtract, multiply, or divide them as you wish. This is what computers are best at. To see this algebra at work, type the following command at the command prompt:

>>> yp = x0 + x1 >>> ym = x1 - x0 >>> yt = x0*x1 >>> yd = x1/x0 >>> print(yp,ym,yt,yd)

You are now officially scientifically computing.

## Computers and logic

If the only thing computers could do were algebra, their impact on
scientific computing would be limited. The fact that computers are also
good at logic is what makes complex programs possible. You may be familiar
with *if this, then that* (IFTTT)
logic. This isn't exactly what I'm talking about, but it's close. I'm
referring to program flow control, or the ability to execute a line or
block (a group of lines) of code only under certain conditions and other
lines or blocks of code under other conditions. To see what this really
means, type the following command:

>>> x1 = 2.0 >>> if x1 < 0: x = 0 print("Negative switched to zero") elif x1 == 0: print ("Zero") else: print ("x1 is positive")

That code is an example of an `if`

block, where
`elif`

is short for *else if,* and `else`

is
executed if the two (or as many as you need) prior code block tests fail.
For a more detailed explanation, check out More
Control Flow Tools in the Python documentation.

The power behind many algorithms in scientific computing is related to the
ability to execute the same code block multiple times with different data.
This is where loops come in handy. Consider the following code snippet,
which uses the Python built-in function `range`

to generate a
list of 10 integers, starting with 0:

>>> x0 = 1.5 >>> for i in range(10): x1 = x0 + i

This code performs the calculation x1 = x0 + i 10 times, starting from i=0 and ending with i=9.

## What's your function?

Functions begin the important programming process of breaking down a large
programming task into a smaller set of subtasks, or *functions.*
Python has built-in functions and external libraries, which I'll explain
later. You can also build your own functions. You create functions by
using the Python keyword `def`

, as shown below,
for the function named `f`

, which receives the input variable
`x`

and returns the value that results from evaluating the
programmed algebraic expression:

>>> def f(x): return x**3 - 5*x**2 + 5*x + 1 >>> x0 = 1 >>> print ("f(x0) = ", f(x0))

To create a function to compute the analytic derivative of the above function, type:

>>> def fp(x): return 3*x**2 - 10*x + 5 >>> x1 = 2 >>> print ("The derivative of f(x) is: ", fp(2))

## File this

So far, you've entered all your Python commands at the command prompt,
which is fine for short, disposable code. But if you're working on a
larger project or simply want to save your work for later, I recommend
creating a new Python file, or *script.* You can do this from the
terminal window by using your favorite text editor. For example, using vi, you
can simply type `vi newton.py`

to create a blank text file
named *newton* with the .py file extension to let everyone (and the
computer, in particular) know this is a Python file. Then, with the file
open, you can start typing your Python commands.

**Note:** Python uses white space to denote code blocks. The
standard convention is to use four spaces to indent a new code block, such
as the code lines that makeup a function, or an `if-then`

block.

Another important aspect of writing programs is *comments*— lines
that tell someone reading your file what the script does. Single-line
comments begin with the pound symbol (`#`

); to create multi-line
comments, precede them with a backslash followed by # (`\#`

),
and follow them with `#\`

. After entering your code, save it
and exit the editor. Then run the code from the terminal window command line
(assuming you're in the same directory as the saved file) by typing
`python newton.py`

.

In scientific computing, it's typically a good idea to break a problem or
task down into smaller problems, or *subtasks.* In Python, these subtasks are
called *modules.* Modules are simply additional Python files (with
the file extension .py) that contain definitions and statements. Prebuilt
modules are also available. You can use any module within your program by
importing it using the `import`

keyword. For example, the math
module contains basic math functions such as sine and cosine; it's
available by using the keyword `import math`

.

## Importing scientific computing power into Python

Two powerful scientific computing modules you'll want to use in Python
are NumPy and SciPy. NumPy contains many powerful
features, but of particular interest here is its ability to
create collections of numbers of the same data type that are assigned to a
single variable, called an *array.* It also has extensive linear
algebra, Fourier transform, and random number capabilities. SciPy is the
overarching scientific computing ecosystem that contains NumPy and
numerous other packages, such as matplotlib, which I talk about in the
next section. The following code provides a quick example
of how to import NumPy and use it in a code snippet:

import numpy as np /* Now we create and assign a list of integers 0 through 9 to x[0] through x[9], effectively creating a one-dimensional NumPy array */ x = np.linspace(10) print(x)

## Using Python to generate graphical output

Generating effective graphical output of data from scientific computing is key to understanding and communicating your results. The standard package in Python to achieve this important goal is the matplotlib module. It's easy to access and use, as you can see:

>>> import numpy as np >>> import matplotlib.pyplot as plt >>> x = np.arange(0, 5, 0.1) >>> y = np.sin(x) >>> plt.plot(x,y) >>> plt.show()

The matplotlib module has commands to control the line type, colors, and style, as well as to save your plot.

## Next steps

The web offers hundreds of sites to help you learn Python and its role in scientific computing. Here are some great resources you can use to learn more:

- For a short example of a scientific computing application created in Python, Daniel Homola created an implementation of Newton's method in just 10 lines of Python code.
- One of my favorite resources is An introduction to Python for scientific computing.
- Looking for a great book? Check out Effective Computation in Physics: Field Guide to Research with Python by Anthony Scopatz.
- A recent and useful reference is A Whirlwind Tour of Python, by Jake VanderPlas, which is from his book Python Data Science Handbook: Essential Tools for Working with Data.
- When you get more advanced or want to go beyond scientific computing in Python, I recommended Python Tricks: A Buffet of Awesome Python Features by Dan Bader.

Happy coding!