Chapter 6 : Functions¶

Example 6.1, Page No 126¶

In [2]:
def dAverage(x1,x2):
av = (x1+x2)/2
return av

print "Enter two numbers:"
dNo1= float(raw_input(""))
dNo2= float(raw_input(""))
dAvg= dAverage(dNo1,dNo2)
print "The average is: ",dAvg

Enter two numbers:
30
20
The average is:  25.0


Example 6.2, Page No 127¶

In [5]:
def min(x,y):
if (x<y):
return x
else:
return y

print "Enter Three integer: "
a=int(raw_input(""))
b=int(raw_input(""))
c=int(raw_input(""))
m=min(a,b)
m=min(m,c)
print m

Enter Three integer:
3
5
2
2


Example 6.3, Page No 129¶

In [11]:
def min(x,y):
if(x<y):
return x
else:
return y
t=0
iNos=range(5)
for t in range(5):
print "Enter integer no",t+1,":"
iNos[t]=int(raw_input(""))

m=iNos[0]

for t in range(5):
m=min(iNos[t],m)

print m,"is the least integer"

Enter integer no 1 :
10
Enter integer no 2 :
3
Enter integer no 3 :
4
Enter integer no 4 :
5
Enter integer no 5 :
7
3 is the least integer


Example 6.4, Page No 131¶

In [6]:
def iLgth(s):
n=0
while(s[n] != '\0'):
n=n+1
return n

cWord=range(30)
cWord=raw_input("Enter a word:")
cWord=cWord + '\0' #by default string array don't appen NULL character hence, it is manually appended
iLen=iLgth(cWord)
print "Length of the word is: ",iLen

Enter a word:bhavin mehta
Length of the word is:  12


Example 6.5, Page No 134¶

In [8]:
def dDiscount(iQty,dLinePrice):
if(dLinePrice>1000):
return 0.15
elif(dLinePrice>500 or iQty>10):
return 0.10
else:
return 0

def dPrice(iNo,dUnitPrice):
dTax=0.25
dLinePr=iNo*dUnitPrice
dDiscPerc=dDiscount(iNo,dLinePr)
return dLinePr*(1-dDiscPerc)*(1+dTax)

print "Enter quantity and unit price: "
iQuantity=int(raw_input(""))
dUnitPrice=float(raw_input(""))

print "To be paid", dPrice(iQuantity,dUnitPrice)

Enter quantity and unit price:
30
50
To be paid 1593.75


Example 6.6, Page No 137¶

In [1]:
def replace1(s,c,cnew):
n=0
s = list(s)
while(s[n]!='\0'):
if(s[n]==c):
s[n]=cnew
n=n+1
print "".join(map(str,s))
a="C:/Mydocumnets/Sheets\0"
print a
replace1(a,'/','-')

C:/Mydocumnets/Sheets
C:-Mydocumnets-Sheets


Example 6.7, Page No 139¶

In [9]:
def word(s):
i=0
j=len(s)
while(i<j):
if((s[i]>='a' and s[i]<='z')or(s[i]>='A' and s[i]<='Z')):
i=i+1
else:
return 0;
return 1;

str=range(100)
str=raw_input("Enter word: ")
while(str):
if(word(str)):
print "A word"
else:
print "No word"
str=raw_input("Enter word: ")

Enter word: john
A word
Enter word: smith
A word
Enter word: john smith
No word
Enter word:


Example 6.8, Page No 143¶

In [ ]:
#import myfunc we have created this header file and its going to work as header file user has to make it
print "To be paid: " + str(dPrice(10,700))

# Code for myfunc Header file is here

"""
def underline(n):
for i in range(n):
print "=",
def dDiscount(iQty,dLinePrice):
if(dLinePrice > 1000):
return 0.15
elif(dLinePrice>500 or iQty>10):
return 0.10
else:
return 0
def dPrice(iNo,dUnitPrice):
dTax = 0.25
dLinePr = iNo * dUnitPrice
dDiscPerc = dDiscount(iNo,dLinePr)
return dLinePr * (1-dDiscPerc) * (1+dTax)
"""