# Physics 256
## Lecture 06 - Functions & Modules




```python
import style
style._set_css_style('../include/bootstrap.css')
```

## Last Time

### [Notebook Link: 05_Functions.ipynb](./05_Functions.ipynb)

- List comprehensions
- Programming challenge

## Today
- Functions
- Modules

<!--
<div class="row">
<div class="span alert alert-success">
<h2> Team programming challenge </h2>
<h3> Leap Years</h3>
Write a function that can determine if a given year is a leap year. Use it to find all leap years since you were born.
<p/>
A  leap year is divisible by four, but not by one hundred, unless it is divisible by four hundred.
</div>
</div>
%load data/leapyear.py
-->

## Modules

Don't reinvent the wheel! If you run into a programming problem, chances are, someone has already solved at least some part of it.  Modules are repositories of software and constants that we can `import` and use in our programs.


```python
# we import a module into our code using the `import` keyword
import math
```


```python
# use `dir` to get a list of methods contained in the module
dir(math)
```


```python
# use a method using a `.`
math.sqrt(1.345)
```


```python
# modules can also contain fundamental constants
π = math.pi
print(f'{π:.16f}')
```


```python
print(math.sqrt.__doc__)
```


```python
# notice the contents of math preceeded and followed by two underscores
print(math.__name__)
```

All modules know what their name is.  More on this soon.

### Working with times and dates


```python
import time
print(time.strftime("%a, %d %b %Y   %H:%M:%S +0000",time.gmtime()))
```

The module name acts as a namespace. This can become cumbersome, for very long module names and we can get around it by importing everything into the standard namespace.


```python
from time import *
print(strftime("%m/%d/%Y %H:%M:%S",gmtime()))
```

<div class="span alert alert-danger">
This is usually considered poor programming practice.  Any thoughts on why?
</div>


```python
# We can deal with the long module name issue by making a short name using the `as` keyword
import math as m
print(m.tan(m.pi))
```


```python
# we can also just import the parts we need
from math import sin,cos
from math import pi as π

print(sin(π/3)**2 + cos(π/3)**2)
```

### Writing modules

Any code or collection of methods we write can be included in a module by writing them in a text editor (i.e. not in the Jupyter notebook or interpreter) and saving them with a unqiue filename `mymodule.py`.  We can treat these as complete python programs that can be run, or we can import them from other scripts to maximize effeciency and build collections of useful libraries.

Modules and scripts can both be named `mymodule.py` and both can contain variables, functions/methods and classes.

** What's the difference?**

* When imported, a module's `__name__` attribute is set to the module's file name, without *.py*.
* When executed as a script, the `__name__` attribute is set to `__main__`.
* Except for special cases, you shouldn't put any major executable code at the top-level. 
* Put code in functions, classes, methods, and guard it with if `__name__ == "__main__"`.


```python
%load ../include/mymodule.py
```


```python
# then from another script (or from the Jupyter notebook) 
# we can import the functions defined in this script

# we need to tell python where the script lives, via the sys module
import sys
sys.path.insert(0, "../include")

mymodule.foo()
```

## Computing $\pi$

Let's put these ideas into practice by writing a module containing functions that compute the value of $\pi$ in various ways.

### Gottfried Wilhelm Leibniz 1646-1716


\begin{equation}
\pi = 4 \sum_{n=1}^\infty \frac{(-1)^{n+1}}{2n-1}
\end{equation}

### Abraham Sharp 1653-1742

\begin{equation}
\pi = \sum_{n=0}^\infty \frac{2(-1)^{n}3^{1/2-n}}{2n+1}
\end{equation}

### Monte Carlo Calculation using `random.random()`




\begin{align}
A_\bigcirc &= \pi \\
A_\Box &= 1
\end{align}


```python

```

8a3cdf69a15702ca8b755da4bf0a86f2c487b06f
ipynb
Jupyter Notebook
4-assets/BOOKS/Jupyter-Notebooks/Overflow/06_FunctionsModules.ipynb
impastasyndrome/Lambda-Resource-Static-Assets
7070672038620d29844991250f2476d0f1a60b0a
MIT
4-assets/BOOKS/Jupyter-Notebooks/Overflow/06_FunctionsModules.ipynb
impastasyndrome/Lambda-Resource-Static-Assets
7070672038620d29844991250f2476d0f1a60b0a
MIT
4-assets/BOOKS/Jupyter-Notebooks/Overflow/06_FunctionsModules.ipynb
impastasyndrome/Lambda-Resource-Static-Assets
7070672038620d29844991250f2476d0f1a60b0a
MIT
2021-11-05T07:48:26.000Z
2021-11-05T07:48:26.000Z
Qwen/Qwen-72B
1. YES
2. YES