User Defined Functions

User defined functions make for neater and more efficient programming.

We have already made use of several library functions in the math, scipy and numpy libraries.


In [4]:
import numpy as np
import scipy.constants as constants
print('Pi = ', constants.pi)


Pi =  3.141592653589793

In [5]:
h = float(input("Enter the height of the tower (in metres): "))
t = float(input("Enter the time interval (in seconds): "))
s = constants.g*t**2/2
print("The height of the ball is",h-s,"meters")


Enter the height of the tower (in metres): 10
Enter the time interval (in seconds): 1
The height of the ball is 5.096675 meters

Link to What's in Scipy.constants: https://docs.scipy.org/doc/scipy/reference/constants.html

Library Functions in Maths

(and numpy)


In [3]:
x = 4**0.5
print(x)
x = np.sqrt(4)
print(x)


2.0
2.0

User Defined Functions

Here we'll practice writing our own functions.

Functions start with

def name(input):

and must end with a statement to return the value calculated

return x

To run a function your code would look like this:

import numpy as np

def name(input)

FUNCTION CODE HERE

return D

y=int(input("Enter y:"))

 D = name(y)

 print(D)

First - write a function to calculate n factorial. Reminder:

$n! = \pi^n_{k=1} k$

~

~

~

~

~

~

~

~

~

~

~

~

~

~


In [1]:
def factorial(n):
    f = 1.0
    for k in range(1,n+1):
        f *= k
    return f

print("This programme calculates n!")
n = int(input("Enter n:"))
a = factorial(10)
print("n! = ", a)


This programme calculates n!
Enter n:10
n! =  3628800.0

Finding distance to the origin in cylindrical co-ordinates:


In [2]:
from math import sqrt, cos, sin

def distance(r,theta,z):
    x = r*cos(theta)
    y = r*sin(theta)
    d = sqrt(x**2+y**2+z**2)
    return d

D = distance(2.0,0.1,1.5)
print(D)


2.5

Another Example: Prime Factors and Prime Numbers

Reminder: prime factors are the numbers which divide another number exactly.

Factors of the integer n can be found by dividing by all integers from 2 up to n and checking to see which remainders are zero.

Remainder in python calculated using

n % k

In [6]:
def factors(n):
    factorlist=[]
    k = 2
    while k<=n:
        while n%k==0:
            factorlist.append(n)
            n //= k
        k += 1
    return factorlist

list=factors(12)
print(list)


[12, 6, 3]

In [7]:
print(factors(17556))


[17556, 8778, 4389, 1463, 209, 19]

In [8]:
print(factors(23))


[23]

The reason these are useful are for things like the below, where you want to make the same calculation many times. This finds all the prime numbers (only divided by 1 and themselves) from 2 to 100.


In [9]:
for n in range(2,100):
    if len(factors(n))==1:
        print(n)


2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

More Extended Example

Exercise 2.11 in Newman - binomial coefficients.


In [ ]: