# Introduction to Functional Programming¶

Computers are particularly useful when the task requires doing the same thing, many time repeatedly. In this notebook we introduce the use of *funtions* and *loops* to let the computer do repeated calculations. And finally demonstrate how to save code in a module that can be imported in your notebook.

**Contents:**

```
from numpy import *
```

## A. Functions¶

In Python we define a function to evaluate a result based on inputs. For example, if you find yourself repeatedly finding the magnitude of a vector, you could define a function to do it. (See the Python Tutorial for much more.)

Define a function with `def`

, then a function name of your choice, then the inputs it needs. End the function with a `return`

statement that provides the result of the computation.

```
def magnitude_and_direction(vec): # define function
"find the magnitude and direction (in deg) of a 2D vector" # optional documentation line
mag = sqrt( sum( vec**2 ) )
angle = arctan2(vec[1],vec[0])
angle = angle * 180/pi # convert to deg
return mag,angle # return these results
```

```
r = array(( 5.5, 3 ))
s = array((-5, -3 ))
magnitude_and_direction(r)
```

(np.float64(6.264982043070834), np.float64(28.61045966596522))

```
magnitude_and_direction( 2*r )
```

(np.float64(12.529964086141668), np.float64(28.61045966596522))

```
magnitude_and_direction( r+s )
```

(np.float64(0.5), np.float64(0.0))

```
m,d = magnitude_and_direction( s )
print(f'magnitude of s = {m:.3f}, at angle {d:.3f} degrees')
```

magnitude of s = 5.831, at angle -149.036 degrees

## B. Loops¶

A code *loop* tells the computer to do something over and over again. There are two basic varieties: the `while`

loop and the `for`

loop.

`while`

loop¶

A `while`

loop executes over and over, as long as a given condition is true. For example, the Fibonacci sequence is defined such that each element is the sum of the previous two: $\left \{ 0,1,1,2,3,5,8,... \right \}$. The following `while`

loop will continue to print out series elements as long as they're under 20.

```
a, b = 0, 1
while b < 20:
print(b)
c = a+b
a = b
b = c
```

1 1 2 3 5 8 13

Here's a `while`

loop to find the smallest number that standard Python allows.

```
small = 1.0
while 1+small > 1:
small = small/2 # cut 'small' in half
print ('smallest value =',small)
```

smallest value = 1.1102230246251565e-16

`for`

loop¶

A `for`

loop will iterate over elements in a list (or array or other sequence).

You could use it to count how many negative values are in a list:

```
things = [ -1.396, 0.62, -0.57566, -0.66, -1.668, 0.247]
count = 0 # starting value
for t in things:
if t < 0: count = count + 1
print('there are',count,'negative values')
```

there are 4 negative values

The `range`

function is often useful in a `for`

statement.

```
for i in range(5,10):
print(i)
```

5 6 7 8 9

Note: the given end point is never part of the

`range`

sequence;`range(10)`

generates 10 values, starting at 0. See more in the tutorial.

## C. Modules¶

Suppose you use a function such as `magnitude_and_direction()`

in many
different notebooks. Rather that rewriting the function in each notebook, you
could save the code in a "module" which can then be imported when needed.

For example there is a notebook titled `physical_constants`

that has several convenient constants for Physics homework.
Take a look at the html version of the notebook.
The constant `deg_per_rad`

is defined there to convert radians to degrees.
To use it here you could import the module:

```
import physical_constants
```

The contents of that module are now available here, but they are in their own "namespace". That means that to access them you precede a variable defined in that module with the module name, followed by a period:

```
physical_constants.deg_per_rad
```

57.29577951308232

Note: you can save a lot of this typing with

tab completion. Type the first couple of letters and hit Tab to automatically complete it (or to see the possible completions).

If you prefer to dump all the variables defined in that module into *this*
notebook's namespace, import it as follows:

```
from physical_constants import *
```

That essentially executes all the code in that module as though it were written here. Now we can write

```
print(f'the mass of an electron is {me} kg')
```

the mass of an electron is 9.109e-31 kg

If you don't want to compromise your namespace (with `from module import *`

).
You can define a variable to import as, like this:

```
import physical_constants as pc
```

Now you have a shortcut to all the stuff in that module.

```
print('there are exactly', pc.cm_per_in, 'cm in one inch')
```

there are exactly 2.54 cm in one inch

### Creating your own module¶

The easiest way to create your own module is to create a notebook with the code
you will want to import. In the `file`

menu, choose `Download as > Python (.py)`

, and put the module in the folder with the notebook that will use it.

Learn more about modules in the Python Tutorial.

*Last modified: Tue October 22 2024, 07:19 AM.*