# Chapter 5: Functions¶

## Example main.c, page no. 157¶

In [1]:
print "Welcome to functions"

Welcome to functions


## Example prtmsg2.c, page no. 158¶

In [3]:
def PrintMesg():
print "PrintMesg, Welcome to functions"
print "Main, Welcome to functions"
PrintMesg()

Main, Welcome to functions
PrintMesg, Welcome to functions


## Example 5.1, page no. 160¶

In [5]:
def cube(i):
return i*i*i
print "The ccube of 10 is", cube(10)
input_int = int(raw_input("Input an integer: "))
print "The cube of ", input_int, "is ", cube(input_int)

The ccube of 10 is 1000
Input an integer: 20
The cube of  20 is  8000


## Example 5.2, page no. 161¶

In [1]:
#there is no concept of function declaration in Python, program will remain same as above
def cube(i):
return i*i*i
print "The cube of 10 is", cube(10)
input_int = int(raw_input("Input an integer: "))
print "The cube of ", input_int, "is ", cube(input_int)

The cube of 10 is 1000
Input an integer: 20
The cube of  20 is  8000


## Example 5.3, page no. 163¶

In [4]:
#\a for the beed would not work in Python

def cube(i):
return i*i*i
print "The cube of 10 is", cube(10)
input_int = int(raw_input("Input an integer: "))
if input_int < 1:
print "Input is invalid!"
else:
print "The cube of ", input_int, "is ", cube(input_int)

The cube of 10 is 1000
Input an integer: -9
Input is invalid!


## Example 5.4, page no. 164¶

In [5]:
#there is no concept of function declaration in Python. So, the program will remain same as above

def cube(i):
return i*i*i
print "The cube of 10 is", cube(10)
input_int = int(raw_input("Input an integer: "))
if input_int < 1:
print "Input is invalid!"
else:
print "The cube of ", input_int, "is ", cube(input_int)

The cube of 10 is 1000
Input an integer: 20
The cube of  20 is  8000


## Example 7, page no. 165¶

In [6]:
def maxfunc(i, j , k):
if i >= j and i >= k:
max = i
elif j >=k :
max = j
else:
max = k
return max
print "Input 3 numbers"
a = int(raw_input("a: "))
b = int(raw_input("b: "))
c = int(raw_input("c: "))
m = maxfunc(a, b, c)
print "The maximum is ", m

Input 3 numbers
a: 4
b: 6
c: 5
The maximum is  6


## Example funded.c, page no. 168¶

In [7]:
def max(a, b):
return a if a > b else b
print "Enter 2 numbers"
i = int(raw_input("i: "))
j = int(raw_input("j: "))
iMax = max(i,j)
print "The maximum of %d and %d is %d" %(i, j, iMax)

Enter 2 numbers
i: 5
j: 7
The maximum of 5 and 7 is 7


## Example square1.c, page no. 169¶

In [8]:
def SquareInt(x):
return x**2
Sq = SquareInt(32)
print "The square of 32 is", Sq

The square of 32 is 1024


## Example 5.5, page no. 170¶

In [10]:
def Min(m, n):
if m > n:
MinNum = n
else:
MinNum = m
return MinNum
print "Enter 2 numbers"
a = int(raw_input("a: "))
b = int(raw_input("b: "))
Small = Min(a,b)
print "The minimum of 2 numbers is ", Small
print "The minimum of 2 numbers is ", Min(a,b)

Enter 2 numbers
a: 32567
b: 32657
The minimum of 2 numbers is  32567
The minimum of 2 numbers is  32567


## Example pval.c, page no. 171¶

In [12]:
def ModifierFunc(Num):
print "In function, the value of Num is %d" %Num
Num = 19
print "In function, after changing, value of Num is: %d" %Num
Num = 100
print "In Main, the value of num is %d" %Num
ModifierFunc(Num)
print "After calling function, the value of Num is %d" %Num

In Main, the value of num is 100
In function, the value of Num is 100
In function, after changing, value of Num is: 19
After calling function, the value of Num is 100


## Example swap1.c, page no. 172¶

In [14]:
def swap(a, b):
temp = a
a = b
b = temp
print "Input 2 integers"
i = int(raw_input("i: "))
j = int(raw_input("j: "))
print "Before Swapping: ", i, j
swap(i, j)
print "After Swapping: ", i , j

Input 2 integers
i: 3
j: 5
Before Swapping:  3 5
After Swapping:  3 5


## Example swap2.c, page no. 173¶

In [17]:
def swap(l):
temp = l[0]
l[0] = l[1]
l[1] = temp
return l
print "Input 2 integers"
i = int(raw_input("i: "))
j = int(raw_input("j: "))
print "Before Swapping: ", i, j
a = [i, j]
l = swap(a)
print "After Swapping: ", l[0] , l[1]

Input 2 integers
i: 3
j: 5
Before Swapping:  3 5
After Swapping:  5 3


## Example 5.6, page no. 174¶

In [18]:
def fact(n):
if n == 0:
lfact = 1
else:
lfact = 1
for i in range(2, n+1):
lfact = lfact * i
return lfact
num = int(raw_input("Enter a positive number: "))
factorial = fact(num)
print "The factorial of %d is %d" %(num, factorial)

Enter a positive number: 5
The factorial of 5 is 120


## Example 5.7, page no. 174¶

In [19]:
def SumTwo(n1, n2):
return n1+n2
def SumThree(n1, n2, n3):
return n1+n2+n3
i = 56
j = 32
SumTwo(3, 4)
SumTwo(i, j), SumThree(100, i, j)

Out[19]:
(88, 188)

## Example 5.8, page no. 175¶

In [3]:
#mistake in the book, it should print both 0 & 1 at the start instead of just 0

def Fib(TotNum):
fLast = 1
sLast = 0
print "Fibonacci numbers: "
print "0 1",
while(TotNum > 2):
CurNum = fLast + sLast
print CurNum,
sLast = fLast
fLast = CurNum
TotNum -= 1
print "Program to generate fibonacci numbers"
print "Enter the total numbers to be generated: ",
n = int(raw_input())
Fib(n)

Program to generate fibonacci numbers
Enter the total numbers to be generated: 5
Fibonacci numbers:
0 1 1 2 3


## Example 5.9, page no. 176¶

In [29]:
def Sum20():
sum = 0
for i in range(1, 21):
sum += i
return sum
print "Program to print the sum of first 20 numbers"
print "The sum of first 20 number is ", Sum20()

 Program to print the sum of first 20 numbers
The sum of first 20 number is  210


## Example 5.10, page no. 176¶

In [3]:
def isPalindrome(string):
len1 = len(string)
if len1 == 0:
return True
if string==string[::-1]:
return True
return False

print "Program to test the given string is a palindrome"
string =  raw_input("Enter a string : ")
if isPalindrome(string):
print "The given string %s is a palindrome"%string
else:
print "The given string %s is not a palindrome"%string

Program to test the given string is a palindrome
Enter a string : ratsdrowninwordstar
The given string ratsdrowninwordstar is a palindrome


## Example ifact.c, page no. 178¶

In [31]:
def calc_fact(num):
fact = 1
for i in range(num, 1, -1):
fact *= i
return fact
n = int(raw_input("Enter an integer: "))
print "The factorial of %d is %d" %(n, calc_fact(n))

Enter an integer: 5
The factorial of 5 is 120


## Example 5.11, page no. 179¶

In [11]:
#output will differ as there is no concept of static in Python
i = 1
def CountNumber(n):
global i
print "In the function the value of n is %d" %n
print "The depth of the call is: %d" %i
i +=1
if n > 1:
CountNumber(n-1)
print "After recurssive the value of i is %d" %i
num = 3
CountNumber(num)

In the function the value of n is 3
The depth of the call is: 1
In the function the value of n is 2
The depth of the call is: 2
In the function the value of n is 1
The depth of the call is: 3
After recurssive the value of i is 4
After recurssive the value of i is 4
After recurssive the value of i is 4


## Example fibrec1.c, page no. 180¶

In [38]:
def uFibr(uNum):
if uNum == 0:
return 0
elif uNum == 1:
return 1
else:
return uFibr(uNum-1)+uFibr(uNum-2)
uTnum = int(raw_input("Enter how many number are to be generated: "))
print "The Fibonacci sequences are: "
for uIndex in range(uTnum):
print "%u" %uFibr(uIndex),

Enter how many number are to be generated: 5
The Fibonacci sequences are:
0 1 1 2 3


## Example fiborec2.c, page no. 181¶

In [23]:
import sys
f1 = 0
f2 = 1
def Fib(n):
global f1,f2
if n < 2:
f1 = 0
f2 = 1
else:
Fib(n-1)
temp = f2
f2 = f1+f2
f1 = temp
print "Number of terms to be generated ?",
n = int(raw_input())
print "Fibonacci sequence up to %d terms: " %n,Fib(n)

Number of terms to be generated ?10
Fibonacci sequence up to 10 terms:  0 1 1 2 3 5 8 13 21 34 None


## Eample 5.13, page no. 184¶

In [3]:
def gcd(p, q):
remainder = p-(p/q*q)
if remainder == 0:
return q
else:
return gcd(q, remainder)
print "Type in any 2 nubers whose GCD is to be found: "
a = int(raw_input("a: "))
b = int(raw_input("b: "))
iGcd = gcd(a, b)
print iGcd
print "GCD of %d and %d is %d" %(a, b, iGcd)

Type in any 2 nubers whose GCD is to be found:
a: 13
b: 45
1
GCD of 13 and 45 is 1


## Example 5.14, page no. 185¶

In [4]:
def hanoi(n, sndl, indl, dndl):
if n != 0:
hanoi(n-1, sndl, dndl, indl)
print "Move disk %d from %c to %c" %(n, sndl, dndl)
hanoi(n-1, indl, sndl, dndl)
snvalue = 'L'
invalue = 'C'
dnvalue = 'R'
print "Enter the number of disks: ",
nvalue = int(raw_input())
print "Tower of Hanoi problem with %d disks" %nvalue
hanoi(nvalue, snvalue, invalue, dnvalue)

Enter the number of disks: 3
Tower of Hanoi problem with 3 disks
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 5.15, page nol 187¶

In [6]:
mid = 0
def binSrch(b, key, low, high):
global mid
if low <= high:
mid = int((low+high)/2)
if key < b[mid]:
high = mid - 1
return binSrch(b, key, low, high)
elif key > b[mid]:
low = mid + 1
return binSrch(b, key, low, high)
elif b[mid] == key:
return mid+1
else:
return 0
n = int(raw_input("Enter the size of array: "))
print "Array elements (ascending order) ?"
a = []
for i in range(n):
a.append(int(raw_input()))
print "Element to be searched ?",
key = int(raw_input())
position = binSrch(a, key, 0, n-1)
if position == 0 :
else:
print "Successful search"
print "%d found at position %d" %(key, position)

Enter the size of array: 6
Array elements (ascending order) ?
2
12
67
89
99
100
Element to be searched ?99
Successful search
99 found at position 5


## Example 5.16, page no. 188¶

In [37]:
def my_max(j, n, a):
if n == 0:
return a[j]
else:
m1 = my_max(j, n/2, a)
m2 = my_max(j + n/2 + 1, n/2, a)
if m1 < m2:
return m2
else:
return m1
def my_min(j, n, a):
if n == 0:
return a[j]
else:
m1 = my_min(j, n/2, a)
m2 = my_min(j + n/2 + 1, n/2, a)
if m1 < m2:
return m1
else:
return m2
print "Finding the maximum and minimum recursively"
print "Number of elements in vector ?"
n = int(raw_input())
print "Vector elements ?"
x = []
for i in range(n):
x.append(int(raw_input()))
i = 0
m = n - 1
maxim = my_max(i, m, x)
print "Maximum of %d elements is %d" %(n, maxim)
i = 0
m = n - 1
minim = my_min(i,m,x)
print "Minimum of %d elements is %d" %(n, minim)

Finding the maximum and minimum recursively
Number of elements in vector ?
8
Vector elements ?
12
34
56
78
54
-12
0
89
Maximum of 8 elements is 89
0 7 [12, 34, 56, 78, 54, -12, 0, 89]
Minimum of 8 elements is -12


## Example 5.17, page no. 189¶

In [38]:
#Command line arguments cannot be done using IPython notebook. Hence, skipping the example


## Example 5.18, page no. 190¶

In [ ]:
#Command line arguments