Chapter 5: Functions

Example 5.1, Page no:87

In [1]:
import math

# tests the sqrt() function:
for i in range(0,6):
    print "\t %d \t %f" %(i,math.sqrt(i))
	 0 	 0.000000
	 1 	 1.000000
	 2 	 1.414214
	 3 	 1.732051
	 4 	 2.000000
	 5 	 2.236068

Example 5.2, Page no:88

In [2]:
import math
# tests the identity sin 2x = 2 sin x cos x:
x = 0
while x < 2:
    print "%f  \t\t %f \t %f" %(x,math.sin(2*x),2*math.sin(x)*math.cos(x))
    x += 0.2
0.000000  		 0.000000 	 0.000000
0.200000  		 0.389418 	 0.389418
0.400000  		 0.717356 	 0.717356
0.600000  		 0.932039 	 0.932039
0.800000  		 0.999574 	 0.999574
1.000000  		 0.909297 	 0.909297
1.200000  		 0.675463 	 0.675463
1.400000  		 0.334988 	 0.334988
1.600000  		 -0.058374 	 -0.058374
1.800000  		 -0.442520 	 -0.442520
2.000000  		 -0.756802 	 -0.756802

Example 5.3, Page no:90

In [3]:
def cube(x):
    # returns cube of x:
    return x*x*x

Example 5.4, Page no:91

In [1]:
def cube(x):
    # returns cube of x:
    return x*x*x

# tests the cube() function:
n=1
while (n != 0):
    n = int(raw_input())
    print  "\tcube( %d ) =  %d" %(n,cube(n))
4
	cube( 4 ) =  64
2
	cube( 2 ) =  8
9
	cube( 9 ) =  729
0
	cube( 0 ) =  0

Example 5.5, Page no:90

In [2]:
def maximum(x,y):
    # returns larger of the two given integers:
    if (x < y):
        return y
    else:
        return x

# tests the max() function:
m = 1
n = 1
while m != 0: 
    m = int(raw_input())
    n = int(raw_input())
    print "\tmax( %d , %d ) = %d" %(m,n,maximum(m,n))
5
2
	max( 5 , 2 ) = 5
0
3
	max( 0 , 3 ) = 3

Example 5.6, Page no:93

In [3]:
def maximum(x,y):
    # returns larger of the two given integers:
    if (x < y):
        return y
    else:
        return x

# tests the max() function:
m = 1
n = 1
while m != 0: 
    m = int(raw_input())
    n = int(raw_input())
    print "\tmax( %d , %d ) = %d" %(m,n,maximum(m,n))
5
2
	max( 5 , 2 ) = 5
0
3
	max( 0 , 3 ) = 3

Example 5.8, Page no:94

In [4]:
# returns larger of the two given integers:

m = 1
n = 1
while m!=0:
    m = int(raw_input())
    n = int(raw_input())
    print "\tmax(%d,%d) = %d" %(m,n, max(m,n))
5
4
	max(5,4) = 5
4
3
	max(4,3) = 4
8
0
	max(8,0) = 8
0
5
	max(0,5) = 5

Example 5.9, Page no:95

In [5]:
def fact(n):
    if (n < 0):
        return 0
    f = 1
    while (n > 1):
        f *= n
        n -= 1
    return f

for i in range(-1,6):
    print fact(i),
0 1 1 2 6 24 120

Example 5.10, Page no:95

In [6]:
def fact(n):
    if (n < 0):
        return 0
    f = 1
    while (n > 1):
        f *= n
        n -= 1
    return f


def perm(n,k):
    # returns P(n,k), the number of permutations of k from n:
    if (n < 0 or k < 0 or k > n):
        return 0
    return fact(n)/fact(n-k)

for i in range(-1,8):
    for j in range(-1,i+2):
        print perm(i,j),
    print ''
0 0 
0 1 0 
0 1 1 0 
0 1 2 2 0 
0 1 3 6 6 0 
0 1 4 12 24 24 0 
0 1 5 20 60 120 120 0 
0 1 6 30 120 360 720 720 0 
0 1 7 42 210 840 2520 5040 5040 0 

Example 5.11, Page no:96

In [8]:
def printDate(m,d,y):
    # prints the given date in literal form:
    if (m < 1 or m > 12 or d < 1 or d > 31 or y < 0):
        print "Error: parameter out of range.\n"
        return
    if m == 1:
        print "January ",
    elif m ==2:
        print "February ",
    elif m==3 :
        print "March ",
    elif m==4:
        print "April ",
    elif m==5:
        print "May ",
    elif m==6:
        print "June ",
    elif m==7:
        print "July ",
    elif m==8:
        print "August ",
    elif m==9:
        print "September ",
    elif m==10:
        print "October ",
    elif m==1:
        print "November ",
    else:
        print "December ",
    print d , ", ",  y 

# tests the printDate() function:
month = 1
while month > 0:
    month = int(raw_input())
    day = int(raw_input())
    year = int(raw_input())
    printDate(month,day,year)
9
12
1989
September  12 ,  1989
0
5
2001
Error: parameter out of range.

Example 5.12, Page no:98

In [4]:
import string
def ispunct(s):
    return all(c in string.punctuation for c in s)
def printCharCategory(c):
    # prints the category to which the given character belongs:
    print "The character [" + c + "] is a ",
    if(c.isdigit()):
        print "digit.\n"
    elif (c.islower()):
        print "lower-case letter.\n"
    elif (c.isupper()): 
        print "capital letter.\n"
    elif (c.isspace()):
        print "white space character.\n"
    elif (ord(c) >= 10 and ord(c) <= 15 or ord(c) == 0):
        print "control character.\n"
    elif (ispunct(c)):
        print "punctuation mark.\n"
    else:
        print "Error.\n"

# prints the category to which the given character belongs;
# tests the printCharCategory() function:
for c in range(128):
    printCharCategory(chr(c))
 The character [] is a  control character.

The character [] is a  Error.

The character [] is a  Error.

The character [] is a  Error.

The character [] is a  Error.

The character [] is a  Error.

The character [] is a  Error.

The character [] is a  Error.

The character [] is a  Error.

The character [	] is a  white space character.

The character [
] is a  white space character.

The character [] is a  white space character.

The character [] is a  white space character.

] is a  white space character.

The character [] is a  control character.

The character [] is a  control character.

The character [] is a  Error.

The character [] is a  Error.

The character [] is a  Error.

The character [] is a  Error.

The character [] is a  Error.

The character [] is a  Error.

The character [] is a  Error.

The character [] is a  Error.

The character [] is a  Error.

The character [] is a  Error.

The character [] is a  Error.

The character [] is a  Error.

The character [] is a  Error.

The character [] is a  Error.

The character [] is a  Error.

The character [] is a  Error.

The character [ ] is a  white space character.

The character [!] is a  punctuation mark.

The character ["] is a  punctuation mark.

The character [#] is a  punctuation mark.

The character [$] is a  punctuation mark.

The character [%] is a  punctuation mark.

The character [&] is a  punctuation mark.

The character ['] is a  punctuation mark.

The character [(] is a  punctuation mark.

The character [)] is a  punctuation mark.

The character [*] is a  punctuation mark.

The character [+] is a  punctuation mark.

The character [,] is a  punctuation mark.

The character [-] is a  punctuation mark.

The character [.] is a  punctuation mark.

The character [/] is a  punctuation mark.

The character [0] is a  digit.

The character [1] is a  digit.

The character [2] is a  digit.

The character [3] is a  digit.

The character [4] is a  digit.

The character [5] is a  digit.

The character [6] is a  digit.

The character [7] is a  digit.

The character [8] is a  digit.

The character [9] is a  digit.

The character [:] is a  punctuation mark.

The character [;] is a  punctuation mark.

The character [<] is a  punctuation mark.

The character [=] is a  punctuation mark.

The character [>] is a  punctuation mark.

The character [?] is a  punctuation mark.

The character [@] is a  punctuation mark.

The character [A] is a  capital letter.

The character [B] is a  capital letter.

The character [C] is a  capital letter.

The character [D] is a  capital letter.

The character [E] is a  capital letter.

The character [F] is a  capital letter.

The character [G] is a  capital letter.

The character [H] is a  capital letter.

The character [I] is a  capital letter.

The character [J] is a  capital letter.

The character [K] is a  capital letter.

The character [L] is a  capital letter.

The character [M] is a  capital letter.

The character [N] is a  capital letter.

The character [O] is a  capital letter.

The character [P] is a  capital letter.

The character [Q] is a  capital letter.

The character [R] is a  capital letter.

The character [S] is a  capital letter.

The character [T] is a  capital letter.

The character [U] is a  capital letter.

The character [V] is a  capital letter.

The character [W] is a  capital letter.

The character [X] is a  capital letter.

The character [Y] is a  capital letter.

The character [Z] is a  capital letter.

The character [[] is a  punctuation mark.

The character [\] is a  punctuation mark.

The character []] is a  punctuation mark.

The character [^] is a  punctuation mark.

The character [_] is a  punctuation mark.

The character [`] is a  punctuation mark.

The character [a] is a  lower-case letter.

The character [b] is a  lower-case letter.

The character [c] is a  lower-case letter.

The character [d] is a  lower-case letter.

The character [e] is a  lower-case letter.

The character [f] is a  lower-case letter.

The character [g] is a  lower-case letter.

The character [h] is a  lower-case letter.

The character [i] is a  lower-case letter.

The character [j] is a  lower-case letter.

The character [k] is a  lower-case letter.

The character [l] is a  lower-case letter.

The character [m] is a  lower-case letter.

The character [n] is a  lower-case letter.

The character [o] is a  lower-case letter.

The character [p] is a  lower-case letter.

The character [q] is a  lower-case letter.

The character [r] is a  lower-case letter.

The character [s] is a  lower-case letter.

The character [t] is a  lower-case letter.

The character [u] is a  lower-case letter.

The character [v] is a  lower-case letter.

The character [w] is a  lower-case letter.

The character [x] is a  lower-case letter.

The character [y] is a  lower-case letter.

The character [z] is a  lower-case letter.

The character [{] is a  punctuation mark.

The character [|] is a  punctuation mark.

The character [}] is a  punctuation mark.

The character [~] is a  punctuation mark.

The character [] is a  Error.

Example 5.13, Page no:99

In [10]:
import math
def isPrime(n):
    # returns True if n is prime, False otherwise:
    sqrtn = math.sqrt(n)
    if (n < 2):
        return False
    # 0 and 1 are not primes
    if (n < 4):
        return True
    # 2 and 3 are the first primes
    if (n%2 == 0):
        return False
    # 2 is the only even prime
    for d in range(3,int(sqrtn+1),2):
        if (n%d == 0):
            return False
        # n has a nontrivial divisor
    return True;

for n in range(0,80):
    if (isPrime(n)):
        print n,
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79

Example 5.14, Page no:100

In [11]:
def isLeapYear(y):
    # returns true iff y is a leap year:
    return (y % 4 == 0 and y % 100 != 0 or y % 400 == 0)

# tests the isLeapYear() function:
n = 2
while n > 1:
    n = int(raw_input())
    if (isLeapYear(n)):
        print "%d is a leap year." % n
    else:
        print "%d is not a leap year." %n
2004
2004 is a leap year.
2006
2006 is not a leap year.
2013
2013 is not a leap year.
0
0 is a leap year.

Example 5.15, Page no: 101

In [14]:
def age():
    # prompts the user to input his/her age, and returns that value:
    while (True):
        print "How old are you: "
        n = int(raw_input())
        if (n < 0):
            print "\a\tYour age could not be negative."
        elif (n > 120):
            print "\a\tYou could not be over 120."
        else:
            return n
        print "\n\tTry again.\n"

a = age();
print "\nYou are %d years old." %a
How old are you: 
-12
	Your age could not be negative.

	Try again.

How old are you: 
125
	You could not be over 120.

	Try again.

How old are you: 
24

You are 24 years old.

Example 5.16, Page no: 102

In [15]:
def swap(x,y):
    # exchanges the values of x and y:
    x[0],y[0] = y[0],x[0]

a = [22.2]
b = [44.4]
print "a = %.2f , b =  %.2f " %(a[0],b[0])
swap(a,b)
print "a = %.2f , b =  %.2f " %(a[0],b[0])
a = 22.20 , b =  44.40 
a = 44.40 , b =  22.20 

Example 5.17, Page no: 104

In [16]:
'''
Note : Python doesn't support pass value by reference. but can be done by passing list.
'''

def f(x,y):
    x[0]= 88
    y[0] = 99

# tests the f() function:
a = [22]
b = [44]
print "a = %.2f , b =  %.2f " %(a[0],b[0])
f(a,b)
print "a = %.2f , b =  %.2f " %(a[0],b[0])
f(2*a,b)
print "a = %.2f , b =  %.2f " %(a[0],b[0])
a = 22.00 , b =  44.00 
a = 88.00 , b =  99.00 
a = 88.00 , b =  99.00 

Example 5.18, Page no: 105

In [17]:
def computeCircle(r):
    # returns the area and circumference of a circle with radius r:
    PI = 3.141592653589793
    area = PI*r*r
    circumference = 2*PI*r
    return area,circumference

# tests the computeCircle() function:
print "Enter radius: "
r = int(raw_input())
a,c = computeCircle(r)
print "area = %.2f , circumference = %.2f" %(a,c)
Enter radius: 
5
area = 78.54 , circumference = 31.42

Example 5.19, Page no: 106

In [5]:
'''
Note : Python passes variable by value and not by reference. So output would be differ.
'''


def f(x,y,z):
    x[0] += z[0]
    y[0] += z[0]
    print "x = %d , y = %d , z = %d" %(x[0],y[0],z[0])

x = [22]
y = [33]
z = [44]

print "x = %d , y = %d , z = %d" %(x[0],y[0],z[0])
f(x,y,z)
print "x = %d , y = %d , z = %d" %(x[0],y[0],z[0])
x[0] = 2*x[0] - 3
f(x,y,z)
print "x = %d , y = %d , z = %d" %(x[0],y[0],z[0])
x = 22 , y = 33 , z = 44
x = 66 , y = 77 , z = 44
x = 66 , y = 77 , z = 44
x = 173 , y = 121 , z = 44
x = 173 , y = 121 , z = 44

Example 5.20, Page no: 107

In [19]:
def cube(x):
    # returns cube of x:
    return x*x*x

# tests the cube() function:
print cube(4)
x = int(raw_input())
y = cube(2*x-3)
print y
64
5
343

Example 5.21, Page no: 108

In [20]:
'''
Python has it's own scope so output would be differ.
'''
x = 11

def f():
    x = 44
    print "In f(): x = %d" % x 

def g():
    print "In g(): x = %d" % x 

x = 22
x = 33
print "In block inside main(): x = %d" % x


print "In main(): x = %d" % x 
print "In main(): ::x = %d" % x 
f()
g()
In block inside main(): x = 33
In main(): x = 33
In main(): ::x = 33
In f(): x = 44
In g(): x = 33

Example 5.22, Page no: 109

In [21]:
def max_(x, y,z=0):
    if x > y and x > y:
        return x
    elif y > x and y > z:
        return y
    else:
        return z
    
        
print max(99,77),  " " , max(55,66,33)
99   66

Example 5.23, Page no: 110

In [22]:
# prints the quotient of two input integers:
print "Enter two integers: "
n = int(raw_input())
d = int(raw_input())
if (d == 0):
    import sys
    sys.exit(0)
print n , "/" , d , " = " , n/d 
Enter two integers: 
8
2
8 / 2  =  4

Example 5.24, Page no: 110

In [23]:
def reciprocal(x):
    #returns the reciprocal of x:
    if (x == 0):
        import sys
        sys.exit(1); # terminate the program
    return 1.0/x

x = float(raw_input())
print reciprocal(x)
25
0.04

Example 5.25, Page no: 111

In [24]:
'''
This function evaluates the third degree polynomial a0 + a1x + a2x2 + a3x3. 
'''
def p(x,a0,a1=0,a2=0,a3=0):
    # returns a0 + a1*x + a2*x^2 + a3*x^3:
    return (a0 + (a1 + (a2 + a3*x)*x)*x)


# tests the p() function:
x = 2.0003
print "p(x,7) = %f" % p(x,7)
print "p(x,7,6) = %f" % p(x,7,6)
print "p(x,7,6,5) = %f" % p(x,7,6,5)
print "p(x,7,6,5,4) = %f" % p(x,7,6,5,4)
p(x,7) = 7.000000
p(x,7,6) = 19.001800
p(x,7,6,5) = 39.007800
p(x,7,6,5,4) = 71.022203