Python for Data Analysis

Module 1 - solutions (writing functions)


Exercise 1

In [1]:
def right_justify(S):
    print(' '*(70-len(S)) + S)
In [2]:
right_justify('Python')
                                                                Python

Exercise 2

In [3]:
import math
def distance(x1,x2,y1,y2):
    return math.sqrt((x1-y1)**2+(x2-y2)**2)
In [4]:
x1, x2, y1, y2= 2, -1, -2, 2
print(distance(x1,x2,y1,y2))
5.0

Exercise 3

In [5]:
def print_twice(word):
    print(word)
    print(word)

def do_twice(func,arg):
    func(arg)
    func(arg)

def do_four(func,arg):
    do_twice(func,arg)
    do_twice(func,arg)
In [6]:
do_twice(print_twice,'spam')
spam
spam
spam
spam
In [7]:
do_four(print_twice, 'spam')
spam
spam
spam
spam
spam
spam
spam
spam

Exercise 4

In [8]:
def factorial(n):
    if n>1:
        return n*factorial(n-1)
    else:
        return 1
In [9]:
print(factorial(3))
print(factorial(4))
6
24