12:USER DEFINED FUNCTIONS

12.4.1, page number:194

In [2]:
def get_a_value():
    return float(input())
print "Enter the Length.."
leng=get_a_value()
print "Enter the Width.."
width=get_a_value()
print "Area = ",leng*width
Enter the Length..
16.8
Enter the Width..
43.7
Area =  734.16

12.5.1, page number:195

In [2]:
def change_index():
    index=5
index=3
print "index = ",index
change_index()
print "index = ",index
index =  3
index =  3

12.5.2, page number:196

In [3]:
def get_a_value():
    return float(input())
def calc_area():
    global leng,width
    return leng*width
print "Enter the Length.."
leng=get_a_value()
print "Enter the Width.."
width=get_a_value()
print "Area = ",calc_area()
Enter the Length..
12.5
Enter the Width..
23.7
Area =  296.25

12.6.1, page number:197

In [1]:
def print_value(k):
    print k
numb=5
print "Value of Expression : ",
print_value(numb*3+2)
Value of Expression :  17

12.7.1, page number:198

In [4]:
def TOL():
    return 0.0001
def sqrt(n):
    if n>0.0:
        guess=0.0
        guess=n/2.0
        while True:
            if ((guess*guess-n) > TOL()) or ((guess*guess-n) < -TOL()):
                temp=guess+n/guess
                guess=temp/2.0
            else:
                break
        return guess
    else:
        return -1.0
            
numb=float(input("Enter number.."))
print "Square Root of",numb,"is",sqrt(numb)
Enter number..17.1
Square Root of 17.1 is 4.13521500873

12.8.1, page number:198

In [1]:
year=0
def leap(n):
    return (n%4 == 0)and(n%100 != 0)or(n%400 == 0)
year=int(input("Enter Year.."))
if leap(year):
    print year,"is leap year"
else:
    print year,"is not leap year"
Enter Year..1984
1984 is leap year

12.9.1, page number:199

In [6]:
def input_value():
    return input()
def area(l,w):
    return l*w
print "Length = "
length=input_value();
print "Width = "
width=input_value();
print "Area = ",area(length,width)
Length = 
12.5
Width = 
23.7
Area =  296.25

12.9.2, page number:200

In [7]:
value=1
def power(n,e):
    global value
    if(e<0):
        return 0
    for index in range(0,e):
        if(index < e):
            value*=n
            index+=1
    return value
            
number=int(input("Enter Integer..."))
exponent=int(input("Enter Exponent..."))
while True:
    if (exponent<0):
        exponent=input("Enter a Non-Negative Integer :")
    else:
        break
print number,"raised to ",exponent," = ",power(number,exponent)
Enter Integer...4
Enter Exponent...2
4 raised to  2  =  16