Chapter 7-Modular Programming with Functions

Example-tax1.cpp, Page no-208

In [1]:
Name=[None]*25
Name=raw_input("Enter name of the 1st person: ")
Salary=float(raw_input("Enter Salary: "))
if(Salary<=90000):
    Tax=Salary*12.5/100
else:
    Tax=Salary*18/100
print "The tax amount for", Name, "is:", Tax
Name=raw_input("Enter name of the 2nd person: ")
Salary=float(raw_input("Enter Salary: "))
if(Salary<=90000):
    Tax=Salary*12.5/100
else:
    Tax=Salary*18/100
print "The tax amount for", Name, "is:", Tax
Enter name of the 1st person: Rajkumar
Enter Salary: 130000
The tax amount for Rajkumar is: 23400.0
Enter name of the 2nd person: Savithri
Enter Salary: 90000
The tax amount for Savithri is: 11250.0

Example-tax2.cpp, Page no-209

In [3]:
def CalculateTax(): #function for calculating tax
    Name=[None]*25
    Name=raw_input("Enter name of the person: ")
    Salary=float(raw_input("Enter Salary: "))
    if(Salary<=90000):
        Tax=Salary*12.5/100
    else:
        Tax=Salary*18/100
    print "The tax amount for", Name, "is:", Tax
CalculateTax()
CalculateTax()
Enter name of the person: Rajkumar
Enter Salary: 130000
The tax amount for Rajkumar is: 23400.0
Enter name of the person: Savithri
Enter Salary: 90000
The tax amount for Savithri is: 11250.0

Example-max1.cpp, Page no-210

In [1]:
def Max(x,y):
    if x>y:
        return x
    else:
        return y
a, b=[int(x) for x in raw_input("Enter two integers <a,b>: ").split()]
c=Max(a,b)
print "max (a, b):", c
Enter two integers <a,b>: 20 10
max (a, b): 20

Example.cpp, Page no-214

In [4]:
def Max(x,y):
    if x>y:
        return x
    else:
        return y
a, b=[int(x) for x in raw_input("Enter two integers <a,b>: ").split()]
c=Max(a,b)
print "max (a, b):", c
Enter two integers <a,b>: 20 10
max (a, b): 20

Example-chart1.cpp, Page no-214

In [5]:
import sys
def PercentageChart(percentage):
    for i in range(percentage/2):
        sys.stdout.write('\x3d')
print "Sridevi : ",
PercentageChart(50)
print "\nRajkumar: ",
PercentageChart(84)
print "\nSavithri: ",
PercentageChart(79)
print "\nAnand   : ",
PercentageChart(74)
Sridevi : ========================= 
Rajkumar: ========================================== 
Savithri: ======================================= 
Anand   : =====================================

Example-chart2.cpp, Page no-216

In [6]:
import sys
def PercentageChart(percentage):
    for i in range(percentage/2):
        sys.stdout.write('\x3d')
m1, m2, m3, m4=[int(x) for x in raw_input("Enter percentage score of Sri, Raj, Savi, An: ").split()]
print "Sridevi : ",
PercentageChart(m1)
print "\nRajkumar: ",
PercentageChart(m2)
print "\nSavithri: ",
PercentageChart(m3)
print "\nAnand   : ",
PercentageChart(m4)
Enter percentage score of Sri, Raj, Savi, An: 52 92 83 67
Sridevi : ========================== 
Rajkumar: ============================================== 
Savithri: ========================================= 
Anand   : =================================

Example-chart3.cpp, Page no-217

In [8]:
import sys
def PercentageChart(percentage, style):
    for i in range(percentage/2):
        sys.stdout.write(style)
m1, m2, m3, m4=[int(x) for x in raw_input("Enter percentage score of Sri, Raj, Savi, An: ").split()]
print "Sridevi : ",
PercentageChart(m1, '*')
print "\nRajkumar: ",
PercentageChart(m2, '\x3D')
print "\nSavithri: ",
PercentageChart(m3, '-')
print "\nAnand   : ",
PercentageChart(m4, '!')
Enter percentage score of Sri, Raj, Savi, An: 55 92 83 67
Sridevi : *************************** 
Rajkumar: ============================================== 
Savithri: ----------------------------------------- 
Anand   : !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Example-ifact.cpp, Page no-218

In [9]:
def fact(n):
    if n==0:
        result=1
    else:
        result=1
        for i in range(2, n+1):
            result*=i
    return result
n=int(raw_input("Enter the number whose factorial is to be found: "))
print "The factorial of", n, "is", fact(n)
Enter the number whose factorial is to be found: 5
The factorial of 5 is 120

Example-namelen.cpp, Page no-219

In [10]:
name=[None]*20
name=raw_input("Enter your name: ")
Len=len(name) #string length
print "Length of your name =", Len
Enter your name: Rajkumar
Length of your name = 8

Example-maths.cpp, Page no-220

In [11]:
import math
num=float(raw_input("Enter any factorial number: "))
num1=math.ceil(num) #ceiling of number
num2=math.floor(num) #floor of number
print "ceil(",num,") =", num1
print "floor(",num,") =", num2
Enter any factorial number: 2.9
ceil( 2.9 ) = 3.0
floor( 2.9 ) = 2.0

Example-swap1.cpp, Page no-221

In [12]:
def swap(x, y): #pass by value swap
    print "Value of x and y in swap before exchange:", x, y
    t=x
    x=y
    y=t
    print "Value of x and y in swap after exchange:", x, y
a, b=[int(x) for x in raw_input("Enter two integers <a,b>: ").split()]
swap(a,b)
print "Value of a and b on swap a, b) in main():", a, b
Enter two integers <a,b>: 10 20
Value of x and y in swap before exchange: 10 20
Value of x and y in swap after exchange: 20 10
Value of a and b on swap a, b) in main(): 10 20

Example-swap2.cpp, Pgae no-222

In [2]:
def swap(x, y): #pass by address swap
    t=x
    x=y
    y=t
    return x, y
a, b=[int(x) for x in raw_input("Enter two integers <a ,b>: ").split()]
a, b = swap(a, b)
print "Value of a and b on swap( a, b ):", a, b
Enter two integers <a ,b>: 10 20
Value of a and b on swap( a, b ): 20 10

Example-swap3.cpp, Page no-224

In [13]:
def swap(x, y): #pass by reference swap
    t=x
    x=y
    y=t
    return x, y
a, b=[int(x) for x in raw_input("Enter two integers <a,b>: ").split()]
a, b = swap(a, b)
print "Value of a and b on swap( a, b):", a, b
Enter two integers <a,b>: 10 20
Value of a and b on swap( a, b): 20 10

Example-ref.cpp, Page no-226

In [5]:
def Max(x,y):
    if x>y:
        return x
    else:
        return y
a, b=[int(x) for x in raw_input("Enter two integers <a, b>: ").split()]
if Max(a,b)==a:
    a=425
else:
    b=425
print "The value of a and b on execution of mx(x, y)=425;..."
print "a =", a, "b =", b
Enter two integers <a, b>: 2 1
The value of a and b on execution of mx(x, y)=425;...
a = 425 b = 1

Example-defarg1.cpp, Page no-228

In [1]:
import sys
def PrintLine(ch='-', RepeatCount=70): #default arguments
    for i in range(RepeatCount):
        sys.stdout.write(ch)
    print ''
PrintLine()
PrintLine('!')
PrintLine('*', 40)
PrintLine('R', 55)
----------------------------------------------------------------------
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
****************************************
RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR

Example-defarg2.cpp, Pgae no-229

In [2]:
import sys
def PrintLine(ch='-', RepeatCount=70, nLines=1): #default arguments
    for i in range(nLines):
        for i in range(RepeatCount):
            sys.stdout.write(ch)
        print ''
PrintLine()
PrintLine('!')
PrintLine('*', 40)
PrintLine('R', 55)
PrintLine('&', 25, 2)
----------------------------------------------------------------------
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
****************************************
RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR
&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&

Example-square.cpp, Page no-230

In [8]:
def sqr(num):
    return num*num
n=float(raw_input("Enter a number: "))
print "Its square =",sqr(n)
print "sqr( 10 ) =", sqr(10)
Enter a number: 5
Its square = 25.0
sqr( 10 ) = 100

Example-swap4.cpp, Page no-231

In [3]:
#different swap functions
def swap_char(x, y):
    t=x
    x=y
    y=t
    return x, y
def swap_int(x, y):
    t=x
    x=y
    y=t
    return x, y
def swap_float(x, y):
    t=x
    x=y
    y=t
    return x, y
ch1, ch2=[str(x) for x in raw_input("Enter two characters <ch1, ch2>: ").split()]
ch1, ch2 = swap_char(ch1, ch2)
print "On swapping <ch1, ch2>:", ch1, ch2
a, b=[int(x) for x in raw_input("Enter two characters <a, b>: ").split()]
a, b = swap_int(a, b)
print "On swapping <a, b>:", a,b
c, d=[float(x) for x in raw_input("Enter two floats <c, d>: ").split()]
c, d = swap_float(c, d)
print "On swapping <c, d>:", c, d
Enter two characters <ch1, ch2>: R K
On swapping <ch1, ch2>: K R
Enter two characters <a, b>: 5 10
On swapping <a, b>: 10 5
Enter two floats <c, d>: 20.5 99.5
On swapping <c, d>: 99.5 20.5

Example-swap5.cpp, Page no-233

In [4]:
def swap(x, y): #function overloading
    t=x
    x=y
    y=t
    return x, y
ch1, ch2=[str(x) for x in raw_input("Enter two characters <ch1, ch2>: ").split()]
ch1, ch2 = swap(ch1, ch2)
print "On swapping <ch1, ch2>:", ch1, ch2
a, b=[int(x) for x in raw_input("Enter two characters <a, b>: ").split()]
a, b = swap(a, b)
print "On swapping <a, b>:", a,b
c, d=[float(x) for x in raw_input("Enter two floats <c, d>: ").split()]
c, d = swap(c, d)
print "On swapping <c, d>:", c, d
Enter two characters <ch1, ch2>: R K
On swapping <ch1, ch2>: K R
Enter two characters <a, b>: 5 10
On swapping <a, b>: 10 5
Enter two floats <c, d>: 20.5 99.5
On swapping <c, d>: 99.5 20.5

Example-show.cpp, Page no-234

In [5]:
def show(val): #function overloading
    if(isinstance(val, int)):
        print "Integer:", val
    if(isinstance(val, float)):
        print "Double:", val
    if(isinstance(val, str)):
        print "String:", val
show(420)
show(3.1415)
show("Hello World!")
Integer: 420
Double: 3.1415
String: Hello World!

Example-swap6.cpp, Page no-236

In [6]:
def swap(x, y):
    t=x
    x=y
    y=t
    return x, y
ch1, ch2=[str(x) for x in raw_input("Enter two characters <ch1, ch2>: ").split()]
ch1, ch2 = swap(ch1, ch2)
print "On swapping <ch1, ch2>:", ch1, ch2
a, b=[int(x) for x in raw_input("Enter two characters <a, b>: ").split()]
a, b = swap(a, b)
print "On swapping <a, b>:", a,b
c, d=[float(x) for x in raw_input("Enter two floats <c, d>: ").split()]
c, d = swap(c, d)
print "On swapping <c, d>:", c, d
Enter two characters <ch1, ch2>: R K
On swapping <ch1, ch2>: K R
Enter two characters <a, b>: 5 10
On swapping <a, b>: 10 5
Enter two floats <c, d>: 20.5 99.5
On swapping <c, d>: 99.5 20.5

Example-sort.cpp, Page no-237

In [1]:
(false, true)=(0, 1) #enum type
type =['false', 'true']
def swap(x, y):
    x, y=y, x
    return x, y
def BubbleSort(a, size):
    swapped='true'
    for i in range(size-1):
        if swapped:
            swapped='false'
            for j in range((size-1)-i):
                if a[j]>a[j+1]:
                    swapped='true'
                    a[j], a[j+1]=swap(a[j], a[j+1])
    return a
a=[int]*25
print "Program to sort elements..."
size=int(raw_input("Enter the size of the integer vector <max-25>: "))
print "Enter the elements of the integer vector..."
for i in range(size):
    a[i]=int(raw_input())
a=BubbleSort(a, size)
print "Sorted Vector:"
for i in range(size):
    print a[i],
Program to sort elements...
Enter the size of the integer vector <max-25>: 5
Enter the elements of the integer vector...
8
6
9
3
2
Sorted Vector:
2 3 6 8 9

Example-linear.cpp, Page no-239

In [7]:
def linear(arr, num):
    for i in range(10):
        if arr[i]==num:
            return i
    return -1
a=[10, 20, 5, 59, 63, 22, 18, 99, 11, 65] # 1-D array
element=int(raw_input("Enter the element to be searched: "))
result=linear(a, element)
if result==-1:
    print element, "is not present in the array"
else:
    print element, "is present at",result, "location in the array"
Enter the element to be searched: 88
88 is not present in the array

Example-funcstk.cpp, Page no-240

In [7]:
def Func(j, k):
    print "In the function the argument values are", j, "..", k
i=99
Func(i+1, i)
In the function the argument values are 100 .. 99

Example-variable.cpp, Page no-241

In [8]:
g=100
def func1():
    g=50
    print "Local variable g in func1() :", g
def func2():
    global g
    print "In func2() g is visible since it is global."
    print "Incremeting g in func..."
    g+=1
print "In main g is visible here since g is global."
print "Assigning 20 to g in main..."
g=20
print "Calling func1..."
func1()
print "func1 returned. g is", g
print "Calling func2..."
func2()
print "func2 returned. g is", g
In main g is visible here since g is global.
Assigning 20 to g in main...
Calling func1...
Local variable g in func1() : 50
func1 returned. g is 20
Calling func2...
In func2() g is visible since it is global.
Incremeting g in func...
func2 returned. g is 21

Example-regvar.cpp, Page no-244

In [1]:
import sys
i=int
name=raw_input("Enter a string: ")
print "The reverse of the string is: ",
for i in range(len(name)-1, -1, -1):
    sys.stdout.write(name[i])
Enter a string: mahatma
The reverse of the string is: amtaham

Example-count.cpp, Page no-245

In [1]:
def PrintCount(Count=[1]):
    print 'Count =', Count[0]
    Count[0]=Count[0]+1
PrintCount()
PrintCount()
PrintCount()
Count = 1
Count = 2
Count = 3

Example-add.cpp, Page no-247

In [1]:
def add(*argc):#variable number of arguments to the function
    result=0
    for i in range(1, argc[0]+1):
        result+=argc[i]
    return result
sum1=add(3, 1, 2, 3)
print "sum1 =", sum1
sum2=add(1, 10)
print "sum2 =", sum2
sum3=add(0)
print "sum3 =", sum3
sum1 = 6
sum2 = 10
sum3 = 0

Example-sum.cpp, Page no-248

In [1]:
def sum(*msg): #variable number of arguments to the function
    total=0
    i=1
    while(msg[i]!=0):
        total+=msg[i]
        i+=1
    print msg[0], total
sum("The total of 1+2+3+4 is", 1, 2, 3, 4, 0)
The total of 1+2+3+4 is 10

Example-rfact.cpp, Page no-250

In [1]:
def fact(num): #recursive function
    if num==0:
        return 1
    else:
        return num*fact(num-1)
n=int(raw_input("Enter the number whose factorial is to be found: "))
print "The factorial of", n, "is", fact(n)
Enter the number whose factorial is to be found: 5
The factorial of 5 is 120

Example-hanoi.cpp, Page no-250

In [4]:
def hanoi(n, left, mid, right): #recursive function
    if n!=0:
        hanoi(n-1, left, right, mid)
        print 'Move disk', n, 'from', left, 'to', right
        hanoi(n-1, mid, left, right)
source='L'
intermediate='C'
destination='R'
nvalue=int(raw_input('Enter number of disks: '))
hanoi(nvalue, source, intermediate, destination)
Enter number of disks: 3
Move disk 1 from L to R
Move disk 2 from L to C
Move disk 1 from R to C
Move disk 3 from L to R
Move disk 1 from C to L
Move disk 2 from C to R
Move disk 1 from L to R

Example Page no-254

In [1]:
def power(x1, y1=None):
    if (isinstance(y1, int)):
        result=1.0
        for i in range(1, y1+1):
            result=result*x1
        return result
    else:
        return x1*x1
x=float(raw_input("Enter the value of x: "))
y=int(raw_input("Enter the value of y: "))
print "power(x, y) =", power(x, y)
print "power(x) =", power(x)
Enter the value of x: 9.5
Enter the value of y: 4
power(x, y) = 8145.0625
power(x) = 90.25