Hour 15: Working with Functions¶

Example 15.1, Page No 245¶

In [9]:
def function_1(x,y):
print "Within Function_1."
return (x+y)
def function_2(x,y):
print "Within Function_2."
return (x+y)

x1=80
y1=10
x2=float
y2=float
x2=100.123456
y2=10.123456
print "Pass function_1 %d" % x1,
print " and %d" % y1
print "Function_1 returns %d" % function_1(x1,y1)
print "Pass function_2 %f" % x2,
print " and %f" % y2
print "Function_1 returns %f" % function_2(x2,y2)

Pass function_1 80  and 10
Within Function_1.
Function_1 returns 90
Pass function_2 100.123456  and 10.123456
Within Function_2.
Function_1 returns 110.246912


Example 15.2, Page No 248¶

In [23]:
import time
def GetDateTime():
print "Within GetDateTime()."
print "Current date and time is %s" % str(time.strftime("%a %b %d %X %Y"))

print "Before the GetDateTime() function is called."
GetDateTime()
print "After The GetDateTime() function is called."

Before the GetDateTime() function is called.
Within GetDateTime().
Current date and time is Mon Nov 10 11:08:33 2014
After The GetDateTime() function is called.


Example 15.3, Page No 253¶

In [6]:
def AddDouble(*args):
result=float
result=0.0
print "The number of arguments is "+ str(len(args))
for i in range(len(args)):
result= result + args[i]
return result

d1=float
d2=float
d3=float
d4=float
d1=1.5
d2=2.5
d3=3.5
d4=4.5

print "Given an argument: %2.1f" % d1

print "Given an argument: %2.1f" % d1,
print " and %2.1f" % d2

print "Given an argument: %2.1f" % d1,
print ", %2.1f" % d2,
print " and %2.1f" % d3

print "Given an argument: %2.1f" % d1,
print ", %2.1f" % d2,
print ", %2.1f" % d3,
print " and %2.1f" % d4

Given an argument: 1.5
The number of arguments is 1
The result returned by AddDouble() is: 1.5

Given an argument: 1.5  and 2.5
The number of arguments is 2
The result returned by AddDouble() is: 4.0

Given an argument: 1.5 , 2.5  and 3.5
The number of arguments is 3
The result returned by AddDouble() is: 7.5

Given an argument: 1.5 , 2.5 , 3.5  and 4.5
The number of arguments is 4
The result returned by AddDouble() is: 12.0