# Chapter 10: Functions

### Example 10.1, Page number: 320

In [1]:
#user defined function

import sys

#Variable Initialization
x = 1
y = 2

#Function definition
return a+b

#Function call

#Result
sys.stdout.write("z = %d"%(z))

z = 3

### Example 10.2, Page number: 321

In [2]:
#Call user-defined function at different places.

import sys

#Function definitions
def y():
sys.stdout.write(" Y")
return

def a():
sys.stdout.write(" A")
y()
return

def b():
sys.stdout.write(" B")
a()
return

def c():
a()
b()
sys.stdout.write(" C")
return

def d():
sys.stdout.write(" D")
c()
b()
a()
return

#Function calls
y()
a()
b()
c()
d()

 Y A Y B A Y A Y B A Y C D A Y B A Y C B A Y A Y

### Example 10.3, Page number: 323

In [3]:
#Using similar variable names in different functions.

import sys

#Function definition
def fun():
b = 20
c = 10
sys.stdout.write("\nIn fun() B = %d  C = %d"%(b,c))
return

#Variable Initialization
b = 10
c = 5

#Result
sys.stdout.write("\nIn main() B = %d  C = %d"%(b,c))
fun()

In main() B = 10  C = 5
In fun() B = 20  C = 10

### Example 10.4, Page number: 323

In [6]:
#Global variables on different functions.

import sys

#Global Variable Initialization
b = 10
c = 5

def fun():
global b
b += 1
global c
c -= 1
sys.stdout.write("\nIn fun() B = %d  C = %d"%(b,c))
return

#Result
sys.stdout.write("\nIn main() B = %d  C = %d"%(b,c))
fun()
b += 1
c -= 1
sys.stdout.write("\nAgain In main() B = %d C = %d"%(b,c))

In main() B = 10  C = 5
In fun() B = 11  C = 4
Again In main() B = 12 C = 3

### Example 10.5, Page number: 325

In [1]:
#Using return statement in different ways

import sys

#Function definition
def pass1(a):
if a == 0:
return;
else:
return a*a*a

#Variable Initialization
x = int(raw_input("Enter value of x : "))

#Function call & Result
if x != 1 or x > 0:
y = pass1(x)

#There is no switch statement in python, so if..else statement
if y == 1:
sys.stdout.write("The value returned is %d"%(y))
else:
sys.stdout.write("The Cube of %d is : %d"%(x,y))


Enter value of x : 5
The Cube of 5 is : 125

### Example 10.6, Page number: 327

In [4]:
#Display message using user defined function

import sys

#Function definition
def message():
sys.stdout.write("Have a nice day")

#function call
message()

Have a nice day

### Example 10.7, Page number: 328

In [5]:
#Display Alphabets 'A','B' and 'C' using functions

import sys

#Functions definitions
def a():
sys.stdout.write("\nA")

def b():
sys.stdout.write(" B")

def c():
sys.stdout.write(" C")

#Function call
a()
b()
c()

A B C

### Example 10.8, Page number: 329

In [2]:
#Send value to user defined function and display results

import sys

#Function Definition
def dat(x,y,z):
sys.stdout.write("Date = %d/%d/%d"%(x,y,z))

#Variable Initialization
d = int(raw_input("Enter date dd/mm/yy"))
m = int(raw_input("Enter date dd/mm/yy"))
y = int(raw_input("Enter date dd/mm/yy"))

#function call & Result
dat(d,m,y)

Enter date dd/mm/yy12
Enter date dd/mm/yy12
Enter date dd/mm/yy2001
Date = 12/12/2001

### Example 10.9, Page number: 330

In [7]:
#Square of number using user defined function

import sys

#function definition
def sqr(k):
sys.stdout.write("\n%d"%(k*k))

#Variable Initialization
j = 0

#Function call & Result
for j in range(1,5):
sqr(j)

1
4
9
16

### Example 10.10, Page number: 330

In [3]:
#Pass the value to main() function

import sys

#There is no main function in python
sys.stdout.write("\nNumber of command line arguments J = %d"%(len(sys.argv)))

Number of command line arguments J = 6

### Example 10.11, Page number: 331

In [3]:
#Pass and return values to user defined function.

import sys

#Function Definitions
def dat(x,y,z):
sys.stdout.write("\nToday = %d/%d/%d"%(x,y,z))
x += 1
return x

#Variable Initialization
d = int(raw_input("Enter Date dd/mm/yy : "))
m = int(raw_input("Enter Date dd/mm/yy : "))
y = int(raw_input("Enter Date dd/mm/yy : "))

#Function call
t = dat(d,m,y)

#Result
sys.stdout.write("\nTomorrow = %d/%d/%d"%(t,m,y))

Enter Date dd/mm/yy : 12
Enter Date dd/mm/yy : 12
Enter Date dd/mm/yy : 2001

Today = 12/12/2001
Tomorrow = 13/12/2001

### Example 10.12, Page number: 332

In [4]:
#Send and recieve values to user defined function

import sys

#Function definition
def sum1(x,y,z):
return x+y+z

#Variable Initialization
a = int(raw_input("Enter Three Numbers : "))
b = int(raw_input("Enter Three Numbers : "))
c = int(raw_input("Enter Three Numbers : "))

#Function call
s = sum1(a,b,c)

#Result
sys.stdout.write("Sum = %d"%(s))

Enter Three Numbers : 7
Enter Three Numbers : 5
Enter Three Numbers : 4
Sum = 16

### Example 10.13, Page number: 333

In [5]:
#Recieve values from user defined function without passing any
#value through main().

import sys

#Function definition
def sum1():
x = int(raw_input("Enter Three Numbers : "))
y = int(raw_input("Enter Three Numbers : "))
z = int(raw_input("Enter Three Numbers : "))
return x+y+z

#Function call
s = sum1()

#Result
sys.stdout.write("Sum = %d"%(s))

Enter Three Numbers : 3
Enter Three Numbers : 5
Enter Three Numbers : 4
Sum = 12

### Example 10.14, Page number: 333

In [6]:
#Return value in the form of address.

import sys

#Function definition
def sum1():
x = int(raw_input("Enter Three Values : "))
y = int(raw_input("Enter Three Values : "))
z = int(raw_input("Enter Three Values : "))
k = x + y + z
return k

#There is no pointer concept in python

#Function call
s = sum1()

#Result
sys.stdout.write("Sum = %d"%(s))

Enter Three Values : 3
Enter Three Values : 5
Enter Three Values : 4
Sum = 12

### Example 10.15, Page number: 334

In [7]:
#Call by value

import sys

#Function Definition
def change(a,b):
k = a
a = b
b = k
sys.stdout.write("\nIn Change() X = %d Y = %d"%(a,b))

#Variable Initialization
x = int(raw_input("Enter Values of X & Y : "))
y = int(raw_input("Enter Values of X & Y : "))

#Function call
change(x,y)

#Result
sys.stdout.write("\nIn main() X = %d Y = %d"%(x,y))

Enter Values of X & Y : 5
Enter Values of X & Y : 4

In Change() X = 4 Y = 5
In main() X = 5 Y = 4

### Example 10.16, Page number: 335

In [8]:
#Call by reference

import sys

#Function Definition
def change(a,b):
k = a
a = b
b = k
sys.stdout.write("\nIn Change() X = %d Y = %d"%(a,b))

#There is no pointer concept in python

#Variable Initialization
x = int(raw_input("Enter Values of X & Y : "))
y = int(raw_input("Enter Values of X & Y : "))

#Function call
change(x,y)

#Result
sys.stdout.write("\nIn main() X = %d Y = %d"%(y,x))

Enter Values of X & Y : 5
Enter Values of X & Y : 4

In Change() X = 4 Y = 5
In main() X = 4 Y = 5

### Example 10.17, Page number: 336

In [9]:
#Return by reference

import sys

#Function Definition
def change(a,b):
c = a + b
d = a - b
return c,d

#Variable Initialization
x = int(raw_input("Enter Values of X & Y : "))
y = int(raw_input("Enter Values of X & Y : "))

#Function call

#Result
sys.stdout.write("\nSubtraction : %d"%(sub))

Enter Values of X & Y : 5
Enter Values of X & Y : 4

Subtraction : 1

### Example 10.18, Page number: 337

In [15]:
#Call by value and reference

k = 0
m = 0

#Function Definition
def other(k,m):
sys.stdout.write("\nAddress of k & m in other() : %u %u"%(id(k),id(m)))

#Result
sys.stdout.write("\nAddress of k & m in main() : %u %u"%(id(k),id(m)))

#Function call
other(k,m)

#there is no pointer concept in python and it uses value tagged method in data storage
#instead of addressing the memory location, values of same variables are tagged together

Address of k & m in main() : 30922996 30922996
Address of k & m in other() : 30922996 30922996

### Example 10.19, Page number: 338

In [17]:
#User defined function as an argument to another function.

#Variable Initialization
y = 2

#Function Definitions
def double(m):
return m*2

def square(k):
return k*k

#Function call
x = double(square(y))

#Result
sys.stdout.write("x = %d"%(x))

x = 8

### Example 10.20, Page number: 338

In [10]:
#Two functions as arguments for another functions

import sys

#Function definitions
def x(a,b):
return abs(a-b)

def y():
y = int(raw_input("Enter First Number : "))
return y

def z():
z = int(raw_input("Enter Second Number : "))
return z

#Function call
d = x(y(),z())

#Result
sys.stdout.write("\nz() - y() = %d"%(d))

Enter First Number : 25
Enter Second Number : 50

z() - y() = 25

### Example 10.21, Page number: 339

In [11]:
#Return only absolute value like abs() function

import sys

#Function Definition
def uabs(y):
if y < 0:
return y * -1
else:
return y

#Variable Initialization
x = int(raw_input("Enter a Negative Value : "))

#Function call
x = uabs(x)

#Result
sys.stdout.write("\nX = %d"%(x))

Enter a Negative Value : -5

X = 5

### Example 10.22, Page number: 340

In [12]:
#Square and cube of an entered number.

import sys

#Function Definitions
def input1():        #Since input() is a built in function in python, input1() is used
k = int(raw_input("Number : "))
return k

def sqr(m):
sys.stdout.write("\nSquare : %d"%(m*m))
return m

def cube(m):
return m*m*m

#Function call and Result
sys.stdout.write("\nCube : %d"%(cube(sqr(input1()))))

Number : 2

Square : 4
Cube : 8

### Example 10.23, Page number: 341

In [13]:
#Assign return value of a function to variable.

import sys

#Function Definition
def input1():
k = int(raw_input("Enter Value of x = "))
return k

#Function call
x = input1()

#Result
sys.stdout.write("\nx = %d"%(x))

Enter Value of x = 5

x = 5

### Example 10.24, Page number: 342

In [14]:
#Addition and subtraction of numbers with return value of function.

import sys

#Function Definition
def input1():
k = int(raw_input("Enter Value of x = "))
return k

def sqr(m):
return pow(m,2)

#Function call
x = sqr(1 - input1() + 1)

#Result
sys.stdout.write("\nSquare = %d"%(x))

Enter Value of x = 5

Square = 9

### Example 10.25, Page number: 343

In [15]:
#Multiplication and division of numbers with return value of function.

import sys

#Function Definition
def input1():
k = int(raw_input("Enter Value of x = "))
return k

def sqr(m):
return pow(m,2)

#Function call
x = sqr(5 * input1()/2)

#Result
sys.stdout.write("\nSquare = %d"%(x))

Enter Value of x = 5

Square = 144

### Example 10.26, Page number: 344

In [16]:
# ++ operator with return value of function

import sys

#Function Definition
def input1():
k = int(raw_input("Enter Value of x = "))
return k

def sqr(m):
return pow(m,2)

#Function call
#There is no ++ operator in python. so += operator is used
y = input1()
y += 1
x = sqr(y)

#Result
sys.stdout.write("\nSquare = %d"%(x))

Enter Value of x = 7

Square = 64

### Example 10.27, Page number: 345

In [17]:
#Use mod(%) with function

import sys

#Function Definition
def j():
x = int(raw_input("Enter a Number : "))
return x

#Function call & Result
if j() %2 == 0:
sys.stdout.write("\nNumber is Even.")
else:
sys.stdout.write("\nNumber is Odd.")

Enter a Number : 5

Number is Odd.

### Example 10.28, Page number: 346

In [18]:
#Conditional operator(?) with function.

import sys

#Function Definitions
def sqr(x):
sys.stdout.write("Square ")
return pow(x,2)

def cube(x):
sys.stdout.write("Cube ")
return pow(x,3)

def y():
return 10

#Variable Initialization
x = int(raw_input("Enter a Number : "))

#Function call
z = sqr(x) if x > y() else cube(x)

#Result
sys.stdout.write(" = %d"%(z))

Enter a Number : 5
Cube  = 125

### Example 10.29, Page number: 346

In [19]:
#compare two return values of functions

import sys

#Function Definitions
def a():
x = int(raw_input("Enter a Number a() : "))
return x

def b():
x = int(raw_input("Enter a Number b() : "))
return x

#Function call and Result
if a() == b():
sys.stdout.write("\nValue of a() & b() are equal")
else:
sys.stdout.write("\nValue of a() & b() are unique")

Enter a Number a() : 5
Enter a Number b() : 5

Value of a() & b() are equal

### Example 10.30, Page number: 347

In [20]:
#Evaluate the equation s = sqr(a() + b()) using function

import sys

#Function Definitions
def a():
a = int(raw_input("Enter value of a : "))
return a

def b():
b = int(raw_input("Enter value of b : "))
return b

def sqr(x):
return x*x

#Function call
s = sqr(a() + b())

#Result
sys.stdout.write("\nSquare of Sum = %d"%(s))

Enter value of a : 5
Enter value of b : 3

Square of Sum = 64

### Example 10.31, Page number: 348

In [21]:
#Evaluate the equation y = x^1+x^2..x^n using function

import sys

#Function Definition
def b(m):
m += 1
#sys.stdout.write("%d"%(m))
return m

#Variable Initialization
x = int(raw_input("Values of 'x' and 'n' : "))
n = int(raw_input("Values of 'x' and 'n' : "))
y = 0
z = 1
m = 0

while(z <= n):
m = b(m)
y = y + pow(x,m)
sys.stdout.write("%d + "%(y))
z += 1

if z >= n:
sys.stdout.write("\nValue of y = %d"%(y))

Values of 'x' and 'n' : 3
Values of 'x' and 'n' : 3
3 + 12 + 39 +
Value of y = 39

### Example 10.32, Page number: 350

In [22]:
#Call user defined function through if statement

import sys

#Function Definition
def a():
a = int(raw_input("Enter value of a :"))
return a

#Function call and Result
if a()%2 == 0:
sys.stdout.write("\nThe number is even.")
else:
sys.stdout.write("\nThe number is odd.")

Enter value of a :5

The number is odd.

### Example 10.33, Page number: 351

In [23]:
#Call user defined function through switch() statement

import sys

#Function Definition
def a():
c = raw_input("Enter Your Choice Square(s), Cube(c), Double(d) : ")
c = c.lower()
return c

#Variable Initialization
x = 5

#There is no switch() statement in python.
c = a()
if c == 's':
sys.stdout.write("\nSquare of %d is %d"%(x,pow(x,2)))
else:
if c == 'c':
sys.stdout.write("\nCube of %d is %d"%(x,pow(x,3)))
else:
if c == 'd':
sys.stdout.write("\nDouble of %d is %d"%(x,x*2))
else:
sys.stdout.write("\nUnexpected Choice printed as it is : %d"%(x))


Enter Your Choice Square(s), Cube(c), Double(d) : D

Double of 5 is 10

### Example 10.34, Page number: 353

In [14]:
#Call function through the for loop

import sys

#Function Definition
def plus(k):
if k == 10:
return 0
else:
return k

#Variable Initialization
m = 1

#Function call & Result
#in python, for loop iterates through a range of number. so while loop is used instead.
while plus(m) != 0:
sys.stdout.write("%3d"%(m))
m += 1


  1  2  3  4  5  6  7  8  9

### Example 10.35, Page number: 354

In [25]:
#Call user defined function through while() loop

import sys

#Function Definition
def y():
x = int(raw_input("Enter a Number : "))
return x

#Function call & Result
while y() != 0:
sys.stdout.write("Value enter is non-zero\n")

Enter a Number : 5
Value enter is non-zero
Enter a Number : 0


### Example 10.36, Page number: 355

In [27]:
#Call user defined function through do while() loop

import sys

#Function Definition
def y():
x = int(raw_input("Enter a Number : "))
return x

#Function call and Result
#There is no do-while loop in python

while y() != 0:
sys.stdout.write("\nValue entered is non-zero\n")

Enter a Number : 5

Value entered is non-zero
Enter a Number : 0


### Example 10.37, Page number: 356

In [28]:
#Initialize an array using functions.

import sys

#Function Definition
def c(m):
n = int(raw_input("Enter Number d[%d]"%(m+1)))
return n

#Variable Initialization
d = [c(i) for i in range(0,5)]

sys.stdout.write("\nArray d[] elements are : ")
for k in range(0,5):
sys.stdout.write("%2d"%d[k])

Enter Number d[1]4
Enter Number d[2]5
Enter Number d[3]6
Enter Number d[4]7
Enter Number d[5]8

Array d[] elements are :  4 5 6 7 8

### Example 10.38, Page number: 357

In [20]:
#Pass array element to the function using call by value method.

import sys

#Function Definition
def show(m,u):
sys.stdout.write("\nnum[%d] = %d"%(m+1,u))

#Variable initialization
num = [12,13,14,15,16,17,18]

#Function call & Result
for k in range(0,7):
show(k,num[k])

num[1] = 12
num[2] = 13
num[3] = 14
num[4] = 15
num[5] = 16
num[6] = 17
num[7] = 18

### Example 10.39, Page number: 358

In [22]:
#Pass array element to the function using call by reference

import sys

#Function Definition
def show(u):
m = 0
sys.stdout.write("\nnum[7] = {")
while m != 7:
#There is no pointer concept in python
sys.stdout.write("%2d,"%(u[m]))
m += 1
sys.stdout.write("\b}")

#Variable Initialization
num = [12,13,14,15,16,17,18]

#Function call
show(num)

num[7] = {12,13,14,15,16,17,18,}

### Example 10.40, Page number: 359

In [23]:
#Array elements in reverse order.

import sys

#Function Definition
def show(u):
m = 6
while m != -1:
sys.stdout.write("\nnum[%d] = %d"%(m,u[m]))
m -= 1

#Variable Initialization
num = [12,13,14,15,16,17,18]

#Function call
#There is no pointer concept in python
show(num)

num[6] = 18
num[5] = 17
num[4] = 16
num[3] = 15
num[2] = 14
num[1] = 13
num[0] = 12

### Example 10.41, Page number: 360

In [24]:
#Copy array elements using user defined function.

import sys

#Function Definition
def cpy(p,m):
j = 0
while j != 5:
m[j] = p[j]
j += 1

#Variable Initialization
a1 = [1,2,3,4,5]
a2 = [0 for i in range(0,5)]

#Function call
cpy(a1,a2)

#Result
sys.stdout.write("Source  Target")
for h in range(0,5):
sys.stdout.write("\n%5d\t%d"%(a1[h],a2[h]))

Source  Target
1	1
2	2
3	3
4	4
5	5

### Example 10.42, Page number: 361

In [29]:
#Read array of other function in main()

import sys

#Function definition
def arry(k):
b = [1,2,3,4,5]
return b[k]

#main() function
for k in range(0,5):
sys.stdout.write("\t%d"%(arry(k)))

	1	2	3	4	5

### Example 10.43, Page number: 361

In [30]:
#Interchange array elements of two arrays using function.

import sys
global a
global b

#Function Definitions
x = int(raw_input(""))
return x

def change(a,b):
#Since there is no pointer concept in python, exchange is done in the function using global variables.
for x in range(0,5):
a[x] = a[x] + b[x]
b[x] = a[x] - b[x]
a[x] = a[x] - b[x]

#Variable Initialization
a = [0 for i in range(0,5)]
b = [0 for i in range(0,5)]

for x in range(0,10):
if x < 5:
else:

#Swapping and Result
sys.stdout.write("\nArray A & B ")

for x in range(0,5):
sys.stdout.write("\n%7d%8d"%(a[x],b[x]))

#There is no pointer concept in python.
change(a,b)

sys.stdout.write("\nNow A  & B")
for x in range(0,5):
sys.stdout.write("\n%7d%8d"%(a[x],b[x]))

1
2
3
4
5
6
7
8
9
0

Array A & B
1       6
2       7
3       8
4       9
5       0
Now A  & B
6       1
7       2
8       3
9       4
0       5

### Example 10.44, Page number: 363

In [30]:
#Read array elements declared in different functions using global
#pointer declaration

import sys

#Function Definition
def call(j):
m = 0
u = [5,1,6,0,6]
q = u
while m != j:
sys.stdout.write("%3d"%(u[m]))
m += 1
sys.stdout.write("\n")

#Variable Initialization
m = 0
k = [3,8,5,2,5]
q = k

#Result
while m != 5:
sys.stdout.write("%3d"%(q[m]))
m += 1

sys.stdout.write("\n")
call(5)

  3  8  5  2  5
5  1  6  0  6


### Example 10.45, Page number: 364

In [7]:
#Sum of 1 to 5 numbers using recursion

import sys
global s

s = 0
#Function definition
def main(x,s):
s = s + x
sys.stdout.write("\nx = %d s = %d"%(x,s))
if x == 5:
return
x += 1
main(x,s)

main(1,s)

x = 1 s = 1
x = 2 s = 3
x = 3 s = 6
x = 4 s = 10
x = 5 s = 15

### Example 10.46, Page number: 365

In [31]:
#Calculate triangular number of a given number with recursion function method

import sys

#Function definition
def tri_num(m):
f = 0
if m == 0:
return f
else:
f = f + m + tri_num(m-1)
return f

#Variable Initialization
n = int(raw_input("Enter a Number : "))

#Function call
t = tri_num(n)

#Result
sys.stdout.write("\nTriangular number of %d is %d"%(n,t))


Enter a Number : 5

Triangular number of 5 is 15

### Example 10.47, Page number: 366

In [47]:
#Display the given string using recursion

import sys
import os
global x

#Variable Initialization
x = 0
str1 = "Have a Good Day"

#Function Definition
def main(x):
if x == len(str1):        #There is no null terminating character in python string
return
else:
if str1[x] == 'H':
os.system('cls')
sys.stdout.write("%c"%(str1[x]))
else:
sys.stdout.write("%c"%(str1[x]))
x += 1
main(x)

#Function call
main(x)

Have a Good Day

### Example 10.48, Page number: 367

In [51]:
#Display the given string 10 times using recursion

import sys
import os

#Function definition
def main(x):
sys.stdout.write("\n%.2d] %s"%(x,str1))
x += 1
if x == 11:
return
else:
if x == 1:
os.system('cls')
main(x)
else:
main(x)

#Variable Initialization
x = 0
str1 = "Have a Good Day"

#Function call
main(x)

00] Have a Good Day
01] Have a Good Day
02] Have a Good Day
03] Have a Good Day
04] Have a Good Day
05] Have a Good Day
06] Have a Good Day
07] Have a Good Day
08] Have a Good Day
09] Have a Good Day
10] Have a Good Day

### Example 10.49, Page number: 368

In [32]:
#Factorial using recursive function.

import sys

#Function Definition
def fact(m):
f = 1
if m == 1:
return 1
else:
f = m * fact(m-1)
return f

#Variable Initialization
x = int(raw_input("Enter a Number : "))

#Function call
f = fact (x)

#Result
sys.stdout.write("\nFactorial of %d is %d"%(x,f))

Enter a Number : 5

Factorial of 5 is 120

### Example 10.50, Page number: 369

In [54]:
#Display address of user defined function

import sys

#Function definition
def show():
sys.stdout.write("\nAddress of function show() is : ")

#Function call
show()

#Result
sys.stdout.write("%u"%(id(show)))

Address of function show() is : 95041520

### Example 10.51, Page number: 369

In [55]:
#Call function using pointer

import sys

#Function definition
def show():
sys.stdout.write("\nAddress of function show() is : ")

#There is no pointer concept in python
p = id(show)
show()
sys.stdout.write("%u"%(id(show)))

Address of function show() is : 95041200

### Example 10.52, Page number: 370

In [57]:
#Display the address of library function.

import sys
import os

#Result

Address of printf() is 60743848
Address of clrscr() is 4774132

### Example 10.53, Page number: 371

In [59]:
#Call main() using pointer to main() function

import sys

#Variable Initilization
x = 0

#Function definition
def main(x):
p = id(main)
x += 1
sys.stdout.write("\nCall %d Address of main() %u"%(x,id(main)))
if x == 3:
return
main(x)

#function call
main(x)

Call 1 Address of main() 95040880
Call 2 Address of main() 95040880
Call 3 Address of main() 95040880
In [ ]: