Functions in Python (contd)

✓ Return value functions

e = math.exp(1.0)
height = radius * math.sin(radians)

def area(radius):
    area = math.pi * r**2
    return area

def area(r):
    return math.pi * r**2

def absolute_value(y):
    if y < 0:
        return -y
    else:
        return y

✓ Some complex functions

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

✓ Composition functions

def circle_area(xc, yc, xp, yp):
    return area(distance(xc, yc, xp, yp))

✓ Boolean Functions – It can return boolean values

def is_divisible(x, y):
    if x % y == 0:
        return True
    else:
        return False

✓ Recursion (contd)

# Factorial series
def factorial(n):
    if n == 0:
        return 1
    else:
        return n*factorial(n-1)

#Fibonacci seies
def fibonacci (n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2)

✓ Checking Types – We can use the built-in function isinstance to verify the type of the argument.

def factorial (n):
    if not isinstance(n, int):
        print 'Factorial is only defined for integers.'
        return None
    elif n < 0:
        print 'Factorial is not defined for negative integers.'
        return None
    elif n == 0:
        return 1
    else:
        return n * factorial(n-1)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s