# Chapter 5 : Fruitful functions¶

### example 5.1 page no :41¶

In [1]:
'''
example 5.1 page no :41
'''
import math
return area;

print area(3)

28.2743338823


### example 5.2 page no :42¶

In [2]:
'''
example 5.2 page no :42
'''

def absoluteValue (x):
if (x < 0):
return -x
else:
return x

print absoluteValue(-3)
print absoluteValue(3)

3
3


### example 5.3 page no :44¶

In [3]:
'''
example 5.3 page no :44
'''

def distance (x1, y1,x2,y2):
dx = x2 - x1
dy = y2 - y1;
print  "dx is " , dx
print "dy is " , dy
return 0.0

distance(10,10,20,20)

dx is  10
dy is  10

Out[3]:
0.0

### example 5.4 page no :44¶

In [4]:
'''
example 5.4 page no :44
'''

def distance (x1, y1,x2,y2):
dx = x2 - x1
dy = y2 - y1;
dsquared = dx*dx + dy*dy;
print "dsquared is " , dsquared
return 0.0;

distance(10,10,20,20)

dsquared is  200

Out[4]:
0.0

### example 5.5 page no :45¶

In [5]:
'''
example 5.5 page no :45
'''
import math
def distance (x1, y1,x2,y2):
dx = x2 - x1
dy = y2 - y1;
dsquared = dx*dx + dy*dy;
return math.sqrt(dsquared)

print distance(10,10,20,20)

14.1421356237


### example 5.6 page no :45¶

In [6]:
'''
example 5.6 page no :45
'''

import math
return area;

def distance (x1, y1,x2,y2):
dx = x2 - x1
dy = y2 - y1;
dsquared = dx*dx + dy*dy;
return math.sqrt(dsquared)

def fred(xc, yc, xp,yp):
radius = distance (xc, yc, xp, yp);
return result;

print fred(10,10,20,20)

628.318530718


### example 5.7 page no :48¶

In [7]:
'''
example 5.7 page no :48
'''
def isSingleDigit(x):
if (x >= 0 and x < 10):
return True
else:
return False;

print isSingleDigit(11)
print isSingleDigit(4)

False
True


### example 5.8 page no :51/53¶

In [8]:
'''
example 5.8 page no :51/53
'''

def factorial (n):
if (n == 0):
return 1;
else:
recurse = factorial (n-1)
result = n * recurse
return result;

print factorial(5)

120


### example 5.9 page no :53¶

In [9]:
'''
example 5.9 page no :53
'''
def fibonacci (n):
if (n == 0 or n == 1):
return 1
else:
return fibonacci (n-1) + fibonacci (n-2)

print fibonacci(5)

8

In [ ]: