Chapter 9, User-Defined Functions

Program 9-1 , Page number: 187

In [1]:
# Using a function as an abbreviation

# In python, the user defined functions have to defined before making a call to them

def chorus() :
	print "%60s"%"With a knick-knack-paddy-whack,"
	print "%60s"%"Give the dog a bone,"
	print "%60s\n"%"This old man went rolling home."

print "This old man, he played two,"
print "He played knick-knack on my thumb,"
chorus()

print "This old man, he played one,"
print "He played knick-knack on my shoe,"
chorus()

print "This old man, he played three,"
print "He played knick-knack on my knee,"
chorus()
This old man, he played two,
He played knick-knack on my thumb,
                             With a knick-knack-paddy-whack,
                                        Give the dog a bone,
                             This old man went rolling home.

This old man, he played one,
He played knick-knack on my shoe,
                             With a knick-knack-paddy-whack,
                                        Give the dog a bone,
                             This old man went rolling home.

This old man, he played three,
He played knick-knack on my knee,
                             With a knick-knack-paddy-whack,
                                        Give the dog a bone,
                             This old man went rolling home.

Program 9-2 , Page number: 189

In [2]:
# Demonstration of one use of a function

def get_an_int() :
	"""RETURNS AN INTEGER"""		# This statement is just a description of the function (specific feature of python)
	return 5

print "Enter the length of a rectangle:",
length = get_an_int()
print length

print "Enter the width:",
width = get_an_int()
print width

print "\nThe area is %d"%(length*width)
Enter the length of a rectangle: 5
Enter the width: 5

The area is 25

Program 9-3 , Page number: 191

In [3]:
# An attempt at communication between functions

def modify_i() :
	i = 3
	
i = 1
print "i is now equal to %d"%i

modify_i()
print "i is now equal to %d"%i
i is now equal to 1
i is now equal to 1

Program 9-4 , Page number: 192

In [4]:
# Demonstration of the use of a global variable

# Making variable global

def get_an_int() :
	return 5

def calc_area() :
	area = length*width

globals()			# The command simply makes all the variables declared so far as global variables
print "Enter the length of a rectangle:",
length = get_an_int()
print length

print "Enter the width:",
width = get_an_int()
print width

calc_area()
print "\nThe area is %d"%(length*width)
Enter the length of a rectangle: 5
Enter the width: 5

The area is 25

Program 9-5 , Page number: 194

In [5]:
# Introduction to parameters

def print_an_int(i) :
	"""The function prints an integer passed as a parameter"""
	print i


n = 3

print "Passing a constant:",
print_an_int(5)

print "\n\nPassing a variable's value:",
print_an_int(n)

print "\n\nPassing the value of an expression:",
print_an_int(n * 4 + 1)
Passing a constant: 5


Passing a variable's value: 3


Passing the value of an expression: 13

Program 9-6 , Page number: 196

In [6]:
# Demonstration of how a procedure cannot modify the contents of a variable passed as a parameter

def modify(i) :
	i = 3

i = 1

print "i is now equal to %d"%i

modify(i)

print "i is now equal to %d"%i
i is now equal to 1
i is now equal to 1

Program 9-7 , Page number: 197

In [7]:
# Hailstones, demonstrating the use of a parameter

def step(i) :
	"""This function returns its parameter i divided by 2 if i is even else it returns i multiplied by 3 and incremented by 1"""
	if (i % 2) :
		return (i * 3 + 1)
	else : 
		return (i / 2)

counter = 0

print "Enter a positive integer",
n = 25
print n

nsave = n

while n > 1 :
	n = step(n)
	counter += 1
	print "Step %4d: n = %4d"%(counter,n)

print "\n\n%d went to 1 in %d steps."%(nsave,counter)
Enter a positive integer 25
Step    1: n =   76
Step    2: n =   38
Step    3: n =   19
Step    4: n =   58
Step    5: n =   29
Step    6: n =   88
Step    7: n =   44
Step    8: n =   22
Step    9: n =   11
Step   10: n =   34
Step   11: n =   17
Step   12: n =   52
Step   13: n =   26
Step   14: n =   13
Step   15: n =   40
Step   16: n =   20
Step   17: n =   10
Step   18: n =    5
Step   19: n =   16
Step   20: n =    8
Step   21: n =    4
Step   22: n =    2
Step   23: n =    1


25 went to 1 in 23 steps.

Program 9-8 , Page number: 200

In [8]:
# Square root program demonstrating a non-integer function and parameter

def EPSILON() :
	"""replacement of #define constant"""
	return 0.0001

def sqrt(n) :
	"""returns the square root of the number supplied as parameter using Newton-Raphson method"""
	if n > 0.0 :
		# The for loop statement given in the example(from the book) is not possible to code in python
		# So, breaking it down to while loop
		guess = n / 2.0
		while (guess * guess - n > EPSILON() or guess * guess - n < -EPSILON()) :
			guess = (guess + n/guess) / 2.0
		return guess
	else :
		return (-1.0)

print "Enter the number whose square root you want:",
x = 17.1
print x

print "The square root of %f is %f"%(x,sqrt(x))
Enter the number whose square root you want: 17.1
The square root of 17.100000 is 4.135215

Program 9-9 , Page number: 201

In [9]:
# Testing for leap years using a boolean function

def is_leap(year) :
	"""A function that returns true if the given year is a leap year else returns false"""
	return (year % 4 == 0 and year % 100 != 0 or year % 400 == 0)

print "Please enter a year:",
year = 2000
print year

if (is_leap(year)) :
	print "%d is a leap year."%year
else :
	print "%d is not a leap year."%year
Please enter a year: 2000
2000 is a leap year.

Program 9-10 , Page number: 203

In [10]:
# Demonstration of the use of multiple parameters

def get_an_int() :
	"""returns a random integer"""
	return 7

def area(length,width) :
	"""returns the area of the rectangle using its parameters length and width"""
	return length * width

print "Enter the length of a rectangle:",
length = get_an_int()
print length

print "Enter the width:",
width = get_an_int()
print width

print "\nThe area is %d."%area(length,width)
Enter the length of a rectangle: 7
Enter the width: 7

The area is 49.

Program 9-11 , Page number: 204

In [11]:
# Illustration of a 2-parameter function: raising a number to a power 

def power(i,x) :
	"""returns the values of i to the power of x"""
	accum = 1
	if x < 0 :
		return 0
	for index in range (0,x,1) :
		accum *= i
	return accum

answer = "y"

while answer == "y" or answer == "Y" :
	print "\nPlease enter an integer:",
	number = 4
	print number

	print "Please enter a non-negative integral power"
	print "     to which the first number is to be raised",
	exponent = 2
	print exponent

	while exponent < 0 :
		print "***\7Please make that a non-negative integer"
		exponent = 2 				# randomly making the exponent non-negative

	print "%d raised to the power %d is %ld."%(number,exponent,power(number,exponent))

	# see if the user wants to keep going

	print "\nAnother calculation? (y/n)",
	answer = "n"
	print answer
Please enter an integer: 4
Please enter a non-negative integral power
     to which the first number is to be raised 2
4 raised to the power 2 is 16.

Another calculation? (y/n) n