Wa,
and
ist
of
1)
ML
Functions
%
"amily
2.1 INTRODUCTION
So far, we have introduced variables, operators, input/output operations, data types and execution of
@ program in Python. The codes we have studied till now have been single, conditional and iterative
Sequence of instructions and were small in size. We can easily work with problems whose solutions
can be written in the form of small Python programs, However, as a problem becomes complex,
the program also increases in size and complexity, and it becomes difficult and cumbersome for a
programmer to keep track of the data and control statements in the whole program.
Thus, Python provides the feature to divide a large program into different smaller modules, These
modules are known as functions which have the responsibility to work upon data for processing, It
is difficult and time-consuming to interpret a large program every time there is a slight modification
in the code, But if that program is divided into a number of small functions (also called sub-
Programs), then the whole task becomes easy and saves a lot of time and effort.
Ifrequired and if it becomes necessary, the sub-programs (or sub-problems) can be further divided
into still smaller programs, and the process of dividing a program into a set of programs of smaller
size can be continued up to any appropriate level.
Therefore, functions provide a systematic way of problem-solving by dividing the given problem
into several sub-problems, finding their individual solutions, and integrating the solutions of
individual problems to solve the original problem.thod or modular approag,
finement me!
stepwise Fel
led
coblem-solving is © w (Fig. 2).
be # z ae approach a8 shown belo’ the task has been divided
or divide an lex In this Ce each of which is performeg
asks, i
This program is one ee a aay gaeparate function.
sequence of state!
Get Function! () =
statements statement Boh
statements er amen
statements eer cnet
statements (ee |
statements |
statements def function? ()+ |
statements statement Patron
statements statement Mh
statements etatement |
statements
prestee def function3()+ |
statenents
statements statemeni function
statements statement
statements statement
statements |
statements def function4 (): |
statements emt, |
statements ceeeen function
statenents Bortasene
statements ot |
statements |
statements
statements
Fig. 2.1: Using Functions to divide and conquera large task
2.2 FUNCTIONS IN PYTHON
Itis simply a group of statements under a
from another part of the program, Consi
constitutes various tasks like registering
TC (transfer certificate) generation,
ny name, ie,
ider an example of School Man,
A dishwasher works |i}
ale n. We put dirty dishe.
drying them out S73! ks like adding detergent a wat
2
ike a functior
her and when we press the
" Washing dishes, and even
a
Computer Science with Python-iDirty Dishes
Function: wash dishes
1. Add water/detergent
2. Wash dishes
3, Dry them
Return Value (Output)
Fig. 2.2: Working of a Dishwasher similar to a Python Function
And, thus, we get clean dishes as a result (output).
Functions are also similar as they take some data as input and, depending upon the instructions/
code given, perform the defined task and give some output in the end.
In Python, we have worked with the script mode in the Python revision chapter, which provides
the capability of retaining our work for future usage. For working in script mode, we need to write
a function in Python and save it in the file having .py extension.
A Python function is written once and is used/called as many times as required.
‘TM: Functions are the most important building blocks for any application in Python and work on the
and conquer approach
> Advantages of Functions:
Functions offer the following advantages over sequential approach of programming:
1, Program handling becomes easier: Only a small part of the program is dealt with at a
time.
2. Code reusability: A Python function can be defined once and used many times, So, it
results in code reuse; we don't need to write the same code more than once.
3. Compact code: While working with functions, a common set of code is written only
once and can be called from any part of the program which reduces lines of code and
programming overheads.
4. Easy updation: In case a function is not used in a program, the same set of code which is
required in multiple programs has to be written repeatedly. Hence, if we wish to make
any change in a formula/expression, we have to make changes at every place, else it will
result in erroneous or undesirable output, With function, however, itis required to make
changes to only one location (which is the function itself),
Functions can be categorized into the following three types:
(Built-in fren uti ben
(i) Modules
(iii) User-defined Functions
0 ———— e—auuable in Python. Python t
re are sger and more powerful. These are
ster Fang module £or using then,
in functions are e f : é
as sel built-in functions tO Rog don't B
poe available in the standard li ra Oe
rae discuss some built-in functior
a Type conversion functions
Python provides built-in functio!
termed as type conversion func
i ikes
j) imt(): The int() function take
i ine() can convert floating-point values to ine ge Oe
the fraction part (Statements 3 and 4). Howé s ri
it will generate an error (Statement 5).
type to another, which ae
ns that convert Valles
tions (Fig. 23())-
any value and conv’
an integer (Statement 1)
nit round off; it chops off
as an argument
erts it into
put it does
give a string value
strQ) function converts its argument into a string (Statement 2).
S55 ]ERE (251) Sateen 1, comets the string argument 10 nek
323
>>>) ste (233
233"
yop] ant (294.56) store 3 converts the float argument integer
334
so>| ant (-34.2) > Statement 4, chop ofthe ating pont number to integer
34
>>] int ("Helo") ——> stctemen 5, generates an eror the argument I string value
Traceback (most recent call last):
File "“
", line 1, in
int (‘Hello')
\ValueBrror: invalid literal for int() with base 10: ‘Hello!
) > statment 2 converts the numeri alive tN,
Fig. 2.3(a): Type Conversion Functions in Python
(il) float{): float() function converts inte;
(Fig2.3(b)). This function treats differe
float (26)
26.0
float (21.76)
21.76
‘float (33425)
58.0
float (1243/4;
12.75, “a
gers and strings into floating-point numbers
types of parameters as explained below:
y
eteat (19,A4aiips
3.aqisy te?) |
float (140.6341)
Traceback (nosy sect ('86.7="
File ecent caiy 1){z20at(!
Float (140-6341)
sould not
vey yy
oat (
c
Omputer Science with Python-Xl7" a le
> If the argument is a number,
float(26) returns 26.0, and float(21.76) ry 2
> Ifthe argument is an expressio Cretan
For example, float(33+25)
> Ifthe argument is a str
pee oe Oe leading +/- sign and a floating point number in
Roat(3.14159) rece te float value represented by this string. For example,
float :
(Q returns the same number as a float, For example,
want: the expression is evaluated and float) returns its value.
Ss 58.0 and float(12+3/4) returns 12.75,
5
In
point number in the correct forma Character other than leading +/~ sign and floating
; at, se
following statements will result in ae float() results in an error. For.example, the
float('40.63+'), float('86,7~"), float(‘35+4/7')
» If the string argument contains alphab , then float() results in an error,
in: i cl
a ie alphabetical character, then float() results i i
Mao) a
ifno argument is passed, float) returns 0.0 as output, k
B) input() function
Itenables us to accept an input in the form of string from the user without evaluating its value.
It provides the most common way to gather input from the keyboard. The function input()
continues to read input text from the user until it encounters a new line.
Forexample, name = input('Enter a name:')
print ('Welcome', name + ‘pleasure to meet you')
name = input ("Enter your name
print ('Welcome'
Output:
Enter your name ; Rinku
Welcome Rinku Pleasure to meet you
The input() function allows to insert a value into a program. input() function returns a string
value that can be converted into integer data type. For example,
> To calculate the Selling price of an item
costPrice = int (input ("Enter Cost Price : =)
Profit = int(input ("Enter Profit : "))
Selling Price = costPrice + Profit
print ("Selling Price : ", Selling_Price) z|
Miia
Output:
Enter Cost Price : 60
Enter Profit : 20
80
Selling Price
Here, int() function is used to convert the
into integer data type.
SS , e 2 7
inputted cost price and profit, which is of string type,(erm Functions
In case of string type argument, As
Meera locicgt etree ASCH values of characters are compared for retrieving
aes using max() and min() functions
Pee SIAN", Membase, “RERte, “agar
The min() function takes two oy more
arguments and returns the smalle:
For example, \s the smallest item,
>o>|y = min(‘hello’, ‘how', tare, vous
9>>|print ("Minimum Value: «, yy” / “YOU'r 'Sir')
Minimum val
Explanatio:
The ree meee code shall print ‘Si’ as the output because the ASCII value ofS! is smallest,
fe? an uppercase letter and less than the rest of the words in lowercase—
h (hello’), a (‘are’) and y (‘you’) whose ASCII codes are 104, 97 and 121 respectively.
[ermine ASCII value of/A, ‘and 0 (zero) is 65,97 and 48 respectively
E) abs() function
The abs() function returns the absolute value of a single number: It takes an integer or float
number as an argument and always returns a positive value, It returns a float or integer
number depending upon an argument.
For exampl
>>>] abs (
50
>>>| abs (45)
45
[>>>] abs (-30.6)
30.6
F) type() function
Ifyou wish to determine the data type of a variable, fe., what type of value doi
to, then type() function can be used.
>>>] type (10)
>>>| type (8.2)
>>>| type (22/7)
>>>| type ('22/7')
>>>| type (-18.6)
>>>|type('Hello Python’)
a
___,- | The Boolean argument given to typel) function shoul
he sca: have Tata eter fr Tue sn caplet)
>>>| type (8 > 5)
s it hold/pointii) pis 0: nis rounde
oy p Se ounded up to.0 digits of decimal and the result is a float value,
‘or example, Pond(12,452,0) returns 12,0 ,
round(12.534,0) returns 13,0
Gil) pis positive intege
8 a posit T: nis rounded : * |
For example, round(12. 452,1) returns 12.5
Tound(12.534,2) returns 12.53 |
iv) pisanegatiy
(w) De gre ) © integer: n is rounded up to p digits before the decimal, The trailing p digits
ed off to 0 in case of negative value ofp. :
Meme ssinEIE) © | round(1234,56,-1) returns 12400 |
Tound(1258.4,-2) returns 1300.0
1) range() function
The range() function is used to define a series of numbers and is particularly useful in j
‘for loops’.
For example,
>>> range (5)
range (0, 5)
The expression range(5) generates a series of integers from zero and ends with 4 (5-1)
To show the list of numbers, we can use the command list(range(n)):
>>> List (range (5))
yee, 2, 3, 4)
® To explicitly define the starting and ending number by specifying the two arguments
for beginning and ending numbers:
Syntax: range (begin, end)
For example,
>>> range (5, 9)
range(5, 9)
To show the list:
>>> list (range (5, 9))
(5, 6, 7, 8]
The above examples of range() demonstrated an increment of 1. We can change the way Python
increments the number by introducing a third argument, the ‘step’. It can be a negative or
positive number, but never zero.
Syntax: range(begin, end, stop)
For example,
>>> range (10, 71, 5)
range (10, 71, 5)
Invoking the list, we'll see this sequence of numbers:
>>> list (range (10, 71, 5)) aT
{10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65,
e—H
1,sees a need for the tasks to | |
2.2.2 Modules lengthier and more complex, shen ar onaining functions and ae af
become le is @ ning 1 varia
As ae goats ‘alled modules. A 1 iy ion code or ance of instructions saved yi,
it0 SI ‘
files.
defined in separate ;
= aa ULE and this approach is knoy,
id, test and maintain.
functions that perform relatey
jnother words,
asmodularization,
d for certain predetiney
When we breaka program into
tasks. There are some common
tasks and they are called libraries.
code in more t
Modules also make it easier to reuse the same
acet of functions that is needed in several different programs
« odule. Then, we can import the module in each program that nee<
‘Once we import a module, we can refer to any of its functions oF vari
tored in a file is called Mol
sier to understan
dule should contain
python that are use
the set of functions st
which makes a program ea
modules, each mot
ly-used modules in
han one program. If we have writtey
we can place those functions in,
is to call one of the functions,
ables in our program.
Importing Modules in a Python Program:
Python provides import keyword to import modules in a program. There are two methods to
import modules:
; _ t
() Importing entire module(s); An entire module can be imported in the current program
using import statement. The syntax to import the entire module is:
import
For example, import math
It gives access to all the functions of math module,
© To import multiple modules in a program, the syntax is:
f dmport import*
‘rexample, from math import+
(pi)
3.14159265359
Print (factorial (¢))a 4 =
To import a particular function of
' the
i from import. ey ee can
a od name>
frommath import sqre
; Ghis}wllimport only sqrt() function from the math module.
x To import multiple functions,
1 from
For example,
frommath import sqrt, Pow, pi
This will import multiple functi
mone (4
eee Hons (sqrt and pow) and (pi) the constant of math module in a
>>>]fzom math import sqrt, Pa
‘math impo: €, Pow,
Zz Print (sqrt(225)) 11’ POW PE
15.0
>>>| print (round (pi, 2))
3.14
>>>| print (pow (4,4))
| [256.0
As is evident from the screenshot, it is not required to use math module prefixed with
the function name as it has already been imported using from statement.
import statement is the simplest and the most common Way to use modules in our code.
For example, import math
‘On executing this statement, Python shall perform three operations:
(@) Search for the file, "math.py~
(b) Create space where modules definition and variable will be created.
(© Execute the statements in the module.
the definitions of the module will become part of the code in which the module was imported,
mort statement does not directly import the functions and constants in the program. To access/use
iny of the functions present in the imported module, we have to specify the name of the module
followed by the name of the function, separated by a dot (also known as a period). This format is called
notation.
ult = math. sqrt (64) #Gives output as 8.0 which gets stored in
rint (result) variable 'result'.
‘one of the functions that belongs to math module. This function accepts an argument and returns
lare root of the argument. Thus, the above statement calls the sqrt() passing 64 as an argument
Ins the square root of the number passed as the argument, i., 8.0, which is then assigned to the
SSE FUNCtIONS seamen e SSSee —
© sqrt(x): Returns the s
Square root of x, ‘Thi r
than 22r9, otherwise senare ena accepts a number which is greater
Print ("math.sqrt (65) :», math ey
Output: math. sqrt (65) + 8.06225774829855
>>> math. sqrt (100)
10.0
>>> math.sart (-64)
Results in run-time ValueError
>>> math. sart (7)
2.6457513110645907
Alternatively,
27> print ("math.sqrt (65) :”, round (math. sqrt (65) ,2))
math.sart (65) : 8.06
Explanation:
The function sqrt() used for calculating the square root of 65 using statement
math.sqrt(65) shall not give a perfect square. Instead, it will generate a higher precision
value of 806225774.
This is to be rounded off to 2 decimal places using round() of math library in Python.
Ques: Write a Python module to display square root of a number using math module.
Ans:
root of a number using
|# Python module to display square roo
# math module
Perea |
aot cal sqrt:
Peele cicet (ince (*xatex/aimebert *))
sq root = math. sqrt (number)
# Display the square root
print ("The square root of ", number, "is", sq root)
cal_sqrt () |
Papasan Sui Mec a EK
Output:
‘Enter a number: 64
‘The square root of 64.0 is 8.0
iv x): Returns the base-10 logarithm of x.
Ieee (nah 20910 (200) :", math. 1og10(100))
math.1ogi0(100) : 2.0
>>> math.1og10 (100.12)
2.0005208409361854
>>> math. 1og10 (100.72)
2.003115717099806
[FIO 1S eR SSS
——@ —string module
string module along with its commonl
in Section 1.11 of Chapter 1
random module (Generating Random Numbers)
rogramming concepts
aaa aoe aaa learnt so far involved situations where we were aware of
as the deterministic approach, eae 4 particular task is to be executed, which is described
nae were afe certain situations/applications that involve games
or simulations which work on non-determini
i inistic a
Bo ere on nonce proach. In these types of situations, random
1) Pseudo-random numbers on Lottery scratch cards,
2) reCAPTCHA (like, in login for
) Pea ce Bin forms) uses a random number generator to define which image is to
3) Computer games involving throwing of dice, picking a number or flipping a coin.
4) Shuffling deck of playing cards, etc,
In Python, random numbers are not enabled implicitly; therefore, we need to invoke random
module or random code library explicitly in order to generate random numbers. The first statement
to be given in a program for generating random numbers is:
>>> import random
The various functions associated with the module are explained as follows:
(i) randrange(): This method generates an integer between its lower and upper argument.
By default, the lower argument is 0 and upper argument is range-1.
Syntax: randrange (stop)
OR
randrange (start, stop)
OR
randrange (start, stop, step)
Example 1(a): To generate random numbers from 0 to 29 (30 excluded),
Alternatively,
>>>]import random 9 [>>>|import random ]
>>>|ran_number = random.randrange(30) | |>>>| random. randrange (30)
>>>| print (ran_number)
aA
b>>
{As is evident from-the above two programs, the randrange(30) shall generate random numbers
from 0 to 29. In the first code, the output is 1 and in the other code, the output is 13.
Example 1(b): To generate a random number from range 10 to 100 with the multiple of 5.
>>>import random
>>>val= random. randrange (10,100, 5)
65
This code shall generate any random number between 10 and 100, which is a multiple of 5.
_ EdO and 1as2
number between :
generates an) TT yumber which is stored as th
‘das the random nu
Explanation:
In the above program, ra
«drange() method
So, in the above case, (0 gets selecte
excluded. O gets
ble ‘ran_index.
index value in the varial ;
‘The element presents at index 0 gets Pri
*computer Science’.
ted) as 2 result the output obtained i,
(ii) random()
‘This function generates a random number from 0 to 2. This function can be used to generate
random floating-point value in the range [0.1, 1.0). It takes no parameters and returns
‘alues uniformly distributed between 0 and 1 (Including 0, but excluding 4). Let us see some
examples to better understand this function.
Example 2(a):
[p55]Ezom random import random
[>>> random ()
| 0.9708572675500727
>>>| zandom()
} 0,5726867077198512
Thus, from the above statements, it is evid
i lent that random() functi i
number each time. The random() functi ee
ion i
aoe 10. can also be written with the following alternative
Example 2(b):
332 |xan_nuaber = random. random()
>>> print (vme 2
+_0,4341822461854127
ited is ;
23 aco gta nunbe:
-1s0029a5s3i 29g
Computer Science with Python-Xi
aT_” LLL
Example 2(4): Program to calculate the sum of the digits of a random 3-digit number.
Petetaate the eine the cigita ecu ciate agit Ga
from random import random
n= random() * 900 + 100
n= int(n)
print (n)
a=n// 100
b= (n // 10) & 10
c=nti0
print(a + b +c)
Output:
789
24
Explanation:
The random() function generates a random fractional number from 0 to 1. When a random
number generated using random() gets multiplied by 900, a random number is obtained from
0 to 899. When we add 100 to it, we get a number from 100 to 999.
Then, the fractional part gets discarded using int() and gets printed on the shell window. In the
next statement, the first digit (the most significant) of the number is extracted by dividing it
with 100 (a = n//100).
The digit at one’s place is extracted by dividing the number by 10. The number obtained as
the quotient further takes mod with 10 to extract its last digit which is the same as the digit
placed in the middle of the original number: For extracting each digit of the number, division
by 10 (c = n%10) is carried out. In the last statement, the sum of the digits is calculated and
displayed on the screen.
(iii) randint()
This function accepts two parameters, a and b, as the lowest and highest number; returns a
number ‘N’ in the inclusive range(a, b); which signifies a<=N<=b, where the endpoints are
included in the range. This function generates a random integer number between two given
numbers. This function is best suited for guessing number applications. The syntax is:
random. randint (a,b)
Here, a is the lower bound and bis the upper bound. In case we input a number N, the result
generated will be a<=N<=b. Ensure that the upper limit is included in randint() function,
Example 3(a): To generate a number between 0 and 9.
See soem : Outpu
print (random. randint (0,9)) fr]
Example 3(b): To generate a number between 0 and 5.
b>>/import random .
‘>>> print (random. randint (0 ,5)) Output:
5 5]
The above function can generate any of the integers between 0 and 5 as output, i.
1,2,3,40r5.
e—ii-
meen FunctionsCS
Output:
Casel: [f4, 6, 6, 7, 8, 9, a9 ELYSEES yy
1 12,13, a7)
Enter the number {,
lElement found at eee io
Case 2:
Pons. 6, 6, 8, 10, 12, 12, 19)
© number to be searche 2
Element found at the inde: Roce
et J
Explanatio
js method returns a random floatin
‘tandom.uniform(x, y)
® is the lower limit and y is the upper limit of random float. The returned random floating point
number is greater than or equal to x and less than y.
'g Point number in between two numbers. The syntax is:
1
>>>|print ("uniform Lottery mumber (1, 100 zandon.
, 100) :", random.uniform(1, 100))
Vaiform Lottery number(1, 100) : 71.74947047337123
hod is used for making a random selection from a sequence like a list, tuple or string, The syntax is:
dom. choice (sequence)
Import random
>>> direction choice = random. choice({'1:East!,
>>> print ("my Direction is :", direction choice)
Ny Direction is: 3:Noreh
West", '3:North, '4:south’})
This method is used to shuffle or swap the contents ofa list (that is, generate a random permutation of
list i | The syntax is:
le (list)
¢ an array/list or tuple but returns reshuffled list.
import random
fruits = ['Apple’, ‘Orange’, ‘Banana’, ‘Pineapple’, 'Apricot']
‘random, shuffle (fruits)
print (fruits)
['apricot', ‘Apple’, ‘Pineapple’, ‘Orange’, 'Banana']
import random
erases = [/apple', ‘Orange’, ‘Banana’, 'Pineapple', ‘Apricot')
random. shuffle (fruits)
print ("Reshuffled Fruits :", fruits)
Reshuffled Fruits : ['Pineappie', ‘Apple’,
random, shuffle (fruits)
print ("Reshuffled Fruits :", fruits)
Reshuffled Fruits : {'Banana', ‘Orange’, ‘Apple
ample, each time we use the function shuffle(), the list elements shall be shuffled
generated will be different every time.
‘Banana’, ‘Apricot', ‘Ozange']
‘apricot!, Pineapple!)faet Fanci ————=
: rant ("
PEINE('T am Learning functions in rython) Function Defnition
|>>>(Zunea (> |
am Learning functions in python eee
Output
Fig,
2.5(a): Function Definition (interactive Mode)
‘The example given below displays a message on sen
a F
Such functions are called vold functions Fa oes and does not contain a return statement.
def funciQ: Yi
Print ("I am learning functions in python")
funcl () |
Function Definition
Funetion cal
[F am learning Functions om eytnon] ovat
Fig. 2.5(b): Function Definition (Script Mode)
Void functions might display something on the screen or have some other effect, but they don’t
have a return value. If we try to assign the result of such a function to a variable, we get a special
value called None.
Alternatively, we can make the function call directly from Python shell also as shown in Fig, 2.5(c).
def funci(Q:
Drint("E an learning functions in eython") | }-—> FuretionDefnton
>>| funed | Funetion call
‘I am learning functions in Python output
DS)
Fig, 2.5(c): Alternative method to call function func1() through shell
Significance of Indentation (Space) in Python
Before we move further with Python functions, it is important that we understand the indentation
rule to declare Python functions. These rules are applicable to other elements of Python as well
like declaring conditions, loops or variable.
Python follows a particular style of indentation to define the code. Since Python functions don’t have
any explicit beginning or end, like curly braces to indicate the start and stop for the function,
they have to rely on this indentation. We now take a simple example with print() function.
CS @ —-tionNow, when we apply same indentation for
gives the expected output oth the,
statements and align them in the same line, it
as shown in Fig. 2.6(d)
Se am esening tu
eee
oe
(jr ameion ee
Fig. 2.6(dh: Same indentation for both print) statements
practical Implementation-3
To write a user-defined function to print a right-angled triangle
def triangle (
Objective: To print a right-;
z eprint @ right-angied triangle
Return Value: None
Approach: To use a print statement for each line of output
print ('*')
print("* *")
Print ("* * #1)
peink(s * + *)
Output:
>] |» invoking the Funetion
2.3 HOW FUNCTION RETURNS A VALUE
Till now we have discussed simple user-defined functions where no value was returned to the calling
function or Python interpreter. Now we shall be discussing the functions with some return values.
Usually, function definitions have the following basic structure:
Syntax: def function_name (arguments):
return
return command in function is used to end the execution of the function call and also specifies what
value is to be returned back to the calling function. Function can take input values as parameters,
execute them and return output (if required) to the calling function with a return statement. The
function returning value to the calling function is termed as fruitful function.
f
'
a &-practical Implementation-6
write a pro}
prose ea i
a add_dift(x, y): fatement returning multiple
aad
a, b = add diff (200,180)
ant ("Tbe sum of two numbers
Ae hoa
print ("The difference of t ee
numbers 13 ",p)
an ——
Output
‘the sum of two nutbers is : 380 |
The difference of two numbers is 20
Inthe Bus vacsrar, we have used a single return statement to return the two values (add, diff)
at the sai . We have specified two variables to receive two values from the called functions.
(ii) By receiving the returned values in the form of a tuple variable.
practical Implementation-7
Modification of Program 6 to compute the basic calculations performed in a calculator,
¥erogram for calculator ca ail
def calc(a,b):
I add = a+b
sub=a-b
ml =a*b
div=a/b
return add, sub, mul, div returning multiple values using return statement |
result = calc(500, 40) |
print (result) |
print("The result can be displayed as: ")
for 4 in result: #displaying multiple values returned as the output
print (4)
Output:
(540, 460, 20000, 12.5)
‘he result can be displayed as:
Learning Tip:
‘A function may or may not return a value.
In a nutshell, while creating functions, we
540 can use two keywords:
460 1. def (mandatory)
20000 2. return (optional)
12.5
Practical Implementation-8
Write a program to implement calculator functions using the concept of user-defined modules.
(Alternative method to Program 7)
We will first create a module named ‘calculate.py’ as per the given code. Then, we shall call this
module through Python shell prompt.
EF, ; a —odule in the script mode and saved
it created and saved, it can be called anytime,
iculator operations, ie., addition, subtraction,
assed as an argument, after invoking the
tatement at Python shell,
Inthe above implementation, we have written the ‘calculate’ mt
it with the name ‘calculate.py’. Once this module
along with passing the values for performing cal
multiplication, division and modulus of two values pé
module (import calculate) first using the import st
followed by the output displayed.
The output of the given program can be calculated by simply calling the function on IDLE, using
fanction call statement as name_of.the module function_name (calculate.add()). A module can
contain executable statements as well as function definitions. These statements are intended to
initialize the module. They are executed only once when the module name is encountered in an
import statement. (They are executed even if the file is run as a script.)
Practical Implementation-9
Write a program to find roots of a quadratic equation.
‘Wrrogram to find roots
st eertarbejt one Of nteabis equation
d= tb arate) 05
seturn (-b + a)/(2 + Ms
a, em qiettyn2i-2) 1 PMI ay
Print(s,
Output:
2.618033988749895
i 98949
is lent from the given
i ry
assigns it to multiple variables.
return without an
exp
case the None value is
the return statement returns a value from a f nal
function and
ession argument j
returned, 'Sused to return from the middl
Of a function : «
in which
ee
Cor
Imbuter Science with Python-*ilFor example,
>>> def func(); 7
Pass
Itis tobe remembered that fu
: neti}
definition are not executed until the new nee defined bet
is called the flow of execution, Staran tot 18 €
is reached.
neers they are called, Statements inside the il
le order in which statements are executed
ratements arg
e exe
cuted one at a time, in order, until a function call
Tals was all about the concept and beh io er-defined
it Shaviour of return statement in a user-defi funeti
defined function.
[ CTM:etum statement returns the value of an
2.4 PARAMETERS AND ARGUMENTS IN FUNCTIONS
Parameters are de
ee baicennition eee (variable(s)) provided in the parentheses when we write
. les contain values 1
Peet eerslclled forcalnn nn lues required by the function to work. These
Pi or Chan One value required by the function to work upon, then all of them wil be
listed in parameter list separated by comma as shown in Fig. 2.7(a)
#70 compute simple interest using function ]
det s x (p, x, penne receive by the function |
zetumn (p+ 5 + ¢ / 100 Ep |
Fig. 2.7(a): Parameters in the function
In the above example, the function S_I (simple interest) is used to calculate simple interest by
getting the values through IDLE, which are termed as arguments
An argument is a value that is passed to the function when itis called. In other words, arguments
are the value(s) provided in function call/invoke statement and passed to the variables of formal
parameters of the function. These arguments are called actual parameters or actual arguments
(Fig. 2.7(b)). List of arguments should be supplied in the same way as parameters are listed.
30, 5)
'S_1 (40001
60000.0
Fig. 2.7(b): Passing Arguments to the function
Bounding of parameters to arguments is done 1:1, so the number and type of arguments should
be same as mentioned in parameter list. If the number of formal arguments and actual eee
differs, then Python will raise an error, Regardless of the arguments (Including the case of no
arguments), a function call must end with parentheses.
literals or variables or expressions—but
hold incoming values; parameters cannot
Arguments in Python can be one of these value RES
the parameters have to be some names, i.e, variables
be literals or expressions.
——————— ®
‘seme Functions
=a ————————— rt esté‘i*@Yr| } Ifthis function is calied with only 0
one
second argument: “rgument, the default value
es ran,
of 1 is assumed for the
Teturn atye
j >>> £4(2)
i 4
> However, the user is f
i ree to chai :
i invoking/calling the function, n®* "te 8€°ond argument from its default value while
>>> £4(2,a=2) #64
és (212) woud also work
Petrone Sscribed into the following four types depending upon the
4 Function with no arguments and no return value
2, Function with arguments but no return value
3. Function with no argument but return value
j 4. Functions with arguments and return value
Let us understand each one of these,
4) Function with no argument and no return value: As the name suggests, these types of
functions do not take any value or argument and do not return any value
[Function Name] [No Parameter Posed]
def welcome ()
print ("ifel10")
PEint ("Good morning")
Function Call jy.
onal
ocd morning
A : In this type of function, parameters are given
ith arguments but no return value: In
a net ccieses separated by comma. Also, the values are passed for the parameter at the
time of function calling.
Example 1: To generate a table for an inputted number.
[dee table (num) : .
for 4 in range (1/3):
print (num, "X";
n= int (input ("Enter Any number
table (n)
num * 4)
oD
e 4
(nm
a CDE)naeExample 5:
pl = int (input (En;
val = nt toube(niy MY Misber: 1)
Print ("umber :
ee ©, vai)
Output:
“ae
Enter Any Number: 5 |
Number + cube |
= 30 |
= 330 |
2.4.2 Types of Arguments
Consider the example
For example,
def f1(x,y):
statement ar | «
C o
£1(20,30) a ee
Here, x, y are formal arguments whereas 20, 30 are actual arguments.
On the basis of examples we have discussed so far, only four types of actual arguments are allowed
in Python. They are:
1, Positional arguments 2. Default arguments
3. Keyword (Name) arguments 4. Variable length arguments
1) Positional arguments: Positional arguments are arguments passed to the actual arguments of
a function in correct positional order, ie., in the same order as in the function header.
7 70 denonstrate Positional argunents
def subtract (a, b):
print (a-b)
‘a gets 100 and b gets 200
[S>>|eubteact (100, 2009}
=100
l>>>| subtract (200, 100) ’ gets 200 and b gets 100)
oe Output: 100
uments must be matched. If we
the number and position of arg
ber of arguments passed, it will
As the given program,
MAN cae thet II change. If we change the num
change their order, the result wil
result in an error.
|ee.
—
th
as [def grect_nsg (name,
Print("Relion, ava
wi
greet_msg(name = yi nay,
Greet_magineg = vooany «MET = G90
[= M0 Mornings, nape aMOzingr)
——— ‘Sonia')
. Output: a
s
Welle Vinay Good Norn:
[Belo Sonta dood worning
Here,
Note:
def grec (name,
z 7 mag) a
Print ('Hell0", nena, msg)
igreet_msg(name = "Vinay <5
sect nag ineg ced sluts Heed Morning) vans
re (ne "Radhis ae = 'Sonia') #valia
lied ka, "doed Morningill — Rinvalid
red, [> Syrtastice
we rae
ave cet erst tts eer met
vise
=a]
eee! |
Advantages of writing functions with keyword arguments are:
¢ Using the function with keyword arguments is easier as we do not need to remember the order
. of the arguments.
= We can specify values of only those parameters which we want to, as other parameters
have default argument values.
Example 7: Consider the following function definition:
def fun(a, b=1, 5S)
print("ais", a, "bis", b, "cis", c)
The function fun() can be invoked in many ways:
4. >>> fun (3)
ais3bisicis5
¥ 2, >>> fun(3, 7, 10)
e ais3bis7¢is10
s 3, >>> fun(25, c = 20)
ais 25bis1c is 20
does not matter.
: Me tenn(c = 20, a - 10) torder co
© ais i0bisic is 20
a ee —f-e gtand 4° call are y
lt value. In the see
pand © WO) a ee values of b and a
fle I stateme i gots the first value 25 a
oe ue to naming, 1-2, ae
value 29 we use Keyword argumen,,
te Hi Bu fis defined before c in
c before
tone is without defay,
ich the firs
hich te Tetion should have at
out of wi
meters OF all to the Funct
in mind:
wera ints should be kept
‘while using keyword argh
suments, te following Po!
have any positional
> An argument list. must —
rguments lowed by any Keyword argument wi ay es co tc
toh ‘ould be a constant only.
parameter shi 5 3
«= Only those parameters which are at the
tend of thelist an be given default value,
«« We cannot have a parameter on the left
with default argument value without
assigning default values to parameters
lying on its right side.
+ The default value is evaluated only once
at the point of function definition.
> Keywords inargumentlist should be from the lis
parameters name only.
> Noparameter should receive value more than once.
> Parameter names corresponding to positional
arguments cannot be used as keywords in the same
calls.
‘On the basis of rules defined above for combining all
three types of arguments, following are the examples
of valid/invalid function call:
Consider the giver 4
eer defined function to calculate average of three numbers:
lef Average (n1,n2,n3=1000) :
return (al+n2+n3) /3
Average{n!=20,n2=40, n3=80) LEGAL
Noy
‘Average(n3=10,n2=7, n1=100) n-default values provided as named argument:
s
LEGAL
‘Average(100, n2=10, n3~15) fea Keyword argument can be in any order
Average(n3=70, 1-90, 100) ILLEGAL Positional argument before the keyword
Average( 100, n1=23, n2=1) Reem Keyword argument be as rd arguments
‘Average(20,num=9,n3=11) Daunte, Positional arguments
Variable length a URLEGALS (Ondetined arcu Sue
ent num
led variable j Pass variable numb,
eI eI
(steisk) symbol in arguments /paramenne to
ython as; ts, Variable
Com,
Puler Science with Python-XlWe can call this function
Y Passin
all these values are represented ee i 7
eee 0 incl
def sum(*n): —— TM Of a tuple, Including zero number, Internally,
total = 0
for 4 inn:
total = totar 4 4
print ("The sun =»,
sum) a)
‘sum (20)
sum (20,30) | :
tuples, dictionary, etc.
2.5.1 Passing Arrays/t
Arrays in basic Python are actually lists that can contain mixed data types. However, for proper
implementation of arrays, we require Numpy library/interface, which ie beyond the scope of this
book, So, we shall be implementing lists as arrays using Python shell.
However, lists are better than arrays as they may hold elements of several data types, whereas
in case of arrays, the elements should be of same data type only and, hence, lists are much more
flexible and faster than arrays, A list can be passed as argument to a function similar to passing
normal variables as arguments to a function.
[#¥arrays(1ist) passing to a function that calculates
#the arithmetic mean of list elements
def 1ist_avg(1st):
2 = Ten(ast)
sum = 0
for 4 in 1st:
sum += i
return sum/1
print ("Input Integers :")
= input ()
a= a.split(
for 4 in range(1en(a)):
alil= int (atil)
avg = List_avg(a)
print ("average i:
print (round(avrg, 2))
Output:
‘Input Integers :
456782
Average is :
‘(5.33
Weceine ————————————‘Enter any string :Punci,
Total nor Of vole metioh® Provias cage |
BONE in the geo Teusah;
—— string Suse ty
re: 13 |
Practical Implementation 11
User-defined functi
tion to accept string 4
times a character is present 8 @S an input and te
7 0 count ay
es nd
ST display the total number of ||
Peso eee ree nc count thy RE
def countchar (str, ch); acs
countenar i Ames a charact
for 4 in str:
if ime on:
count += 1
return count |
# Main code
# function calis
str_input = input ("Enter a,
chi SmpUt ("Enter the chan cet!
ter is
* 48 present inside it
")
“times in the string") |
ists", resuit,
Output:
Enter any string imo count the mumbo;
Enter the character to come tenes Of
e exists 6 times in the string
sme @ character is present
2.5.3 Passing Tuple to a Function
We can also pass a tuple as an argument to a function. Because of its immutable nature, a function can
only access the value of a tuple but cannot modify it. It will become clearer from the following examples:
Example
easing immutable tuple to a function
def func(A):
Amlist(A) #tuple converted to a list
Alo] = Afo]* 2
A[1] = A[1] + 10
print("Value inside function
tup = (100,200)
print (tup)
func (tup)
[petneteuy
Output:
(100, 200)
Malus inside function: [200, 220]
(100, 200)
a)
ent to the function func(). In order to perform
into alist using the method list(). The next two
values are displayed.
remain the same as
—i-
passed as an argum
.d to be converted ii
the changes are reflected when these
re not modified and therefore,
In the above program, tuple ‘tup’ is
mathematical processing, itis require!
statements alter the value of list and, hence,
But outside the function, the values of tuple @of even and odd
splay number Tuy, gutput
:
ete |
3
pare ae ie Progra
| Be mecercs, coed i.
fee freq
=, Qogut meer the total elements in * fF20 as
| io = int (input er et
Beaten “
| oe nec cnster toe bes a
!) tupl = tupi + (num,)
! = tEvenodd (tup1)
see eae Seer nat ate ies
Print ("odd numbers count_stats [1] se
\ Output:
Enter the total elements in a tuple: 10
Enter the number
znter the nunber
Enter the number
Enter the number
znter the number
Enter the number :6
Enter the number
Enter the number :
Enter the number
Enter the number
Even numbers are:
odd numbers ai
2.5.4 Passing Dictionary to a Function
Python also allows us to pass dictionary to a function. Since dictionaries are mutable in nature
function can alter the values of dictionary in place. 2
Let us look at some examples of how to pass dictionary to a function, All
Practical Implementation-13 i
To pass student record as a dictionary to a function and update their marks, an
[#0 pass student record as a dictionary and update their marks >
| def Marks_increase (stud, >)
stud[marks"] t=
| studf"status"] = "Updated
student = {"Rolino"; 1, "Name": "Radhixa"
student2 = {"Rollno": 4, tMame"; “snanenae’
Marks_increase (student ,50) bn
@ (student2, 60)
ident)
Print (student2)
—— a a nn a
F - = Computer Science with Python”Practical Implementation-14
Program to pass a dictionary to a fy o
ne
re
occurrence as value and ret tion with ti @
a ant Tetum aS a dictionary,» °* “ements as keys and frequency of x
def frequencyCount (isti, aicyy = Ao ae
for i in list: 7
if £ not in dict:
ict Ii] =1
dict(i) += 1
return dict
Listi=[4,5,6,5,10,6,5,5, 40,
a=)
frequencycount (2ist1, a)
print (d)
30, 2,4)
Output:
Anything calculated inside a functio
nb
will be deleted once the f Ut not specified as an output (either with return o1
function st r global)
ops running,
Forexample, >>> det £5(x,y): ]
A a= xty
b= x-y 4
return a**2, b¥*2 I
>>> £5(3,2)
(25,1)
If we try to call a or b, we get an error message:
>>> a
Traceback (most recent call last):
Pile "", line 1, in?
NameError: name 'a' is not defined
This brings us to scoping issues, which will be addressed in the next section.
2.6 SCOPE OF VARIABLES
All variables in a program may not be accessible at all locations in that program. This depends on
where you have declared a variable. Scope of variables refers to the part of the program where it is
visible, ie, area where you can refer (use) it. We can say that scope holds the current set of variables
and their values. We will study two types of scope of variables—global scope or local scope.
> Global (module)
+ Names assigned at the to
interpreter i ‘
* Names declared with global keyword in a function
= Can be accessed inside or outside of the function
> Local (function)
* Names assigned inside
» Cannot be accessed outside the function
NE e—f-
Oe es ne
p level of a module, ie., outside of any function, or directly in the
a function definition or loopjable with the same name
ari
sence of local ¥
eal
a ~ rz, so it’s global
tery fee
ar We can access jin the interpre’? ei: tea
; pies t can acces
For example pais Pe eunction 2 oe Beach eo tac
a Pan oF8 170 assigned ins
Spode E001 EXT oe ioe
Ce e of globa: x
+ val ae
eurn y# function, 8° *
retur!
>>> pr£ (5) | |
>>> print (P) ty is given to the local variay,
or We can use the same name: it scopes but the prion
ame names in nt scopt
use the si
For example,
p> as? :
pal
ier. on #this 'a' has no knowledge of the glot
=a jon"
print ("a in function", a)
a! and vice versa
>>> a
2
>>>e5()
a in function 10 : enon
The local variable is deleted as soon as the function stops running. So, the lifeti n
comparison to a global variable.
variable gets over early
For example,
>>> x= 5
>>> import script
Hello world
mos
E
Here, lifetime of a variable is the time for which a variable lives in memory. For global variables.
lifetime is entire program run (i.e., they live in memory as long as the Program is running) ani
for local variables, lifetime is their function's run (ie, as long as their function is being executed)
‘% Value of global variable can be modified using global keyword.
For example,
#same script as before
DS>a=2
>>> def £5():
flobal a ft
re ay Variable a using global keyword
return a
>>>a
2
>>> £5()
2
>>>a
7
Computer Science with Python-X!1
In the previous example, the statement for f(x
main()
(OT Se
For example,
pop a=2
>>> def £ (x):
return x+a
#this function is. fectiv
a 1 effectively, £(x) = x+2
6
>>> a=1
>>> £(4)
: #8ince we set a=1,
£ (x) = x+1 now
>>> £ (x)
I
>>> x
4
s) was x+1, which is carried forward in this example
ly for the function f(x). However, the original value of
gets changed to 5 using x+1 but onl
the argument ‘x’ remains the same.
2.7 FLOW OF EXECUTION OF PROGRAM USING MAIN() AS A FUNCTION j
Including a main() function is not mandatory in Python. It can structure our Python programs in
a logical way that puts the most important components of the program into one function. It can
also make our programs easier for non-Python programmers to read.
Practical Implementation-15 |
We will start with adding a main() function to the ‘prog func4.py’ program below. We will first
define hello() function and then define a main() function.
After defining main() function, we will give print() statement so as to ensure the execution of
main(). After defining the main() function, finally, at the bottom of the program, we will call the
main() function as shown below:
def hello(
print("Hello, World |
def main(): ;
print("This is the main function")
he110()
Output:
This ds the main function |
Helle, World!
a efe shell oF from within,
icitly © d.
ing) explicitly «ene end-
main) or jon in th snctuding the Script for maj,
‘his li
rogram an o
‘within the P? . _ eke ieers
if_name_ 7
main () int the above Com
impleme!
set us take an example to iP! and breadth inputted,
: is of length
practical Implementation-16 a rectangle on the Basis °
a0
Mines progam compute tbe #2
the user as the arguments to this Be
saci
Gof areanectangle(iengeD, PFS io
we ite the aren of Tactangie! | 19
ooo er rent Deeadeh ciao
= ue
wept, value: area - numeric val
area = tength # breadth
Zetura area
doe main(): fi
& le based on user inpt
| cujective: to compute the area of rectang!
Snput Parameter: None
j Return Value: None
i e:')
| int (‘Enter the following values for rectang! i
| Tengthrect = int (input ‘Length: integer value i: :
ill beeadthRect = int (input (‘Breadth : integer value: ')
itt areaRect = areaRectangle (lengthRect, breadthRect)
| print(/area of rectangle is’, areaRect)
eee
| “main 7
i] Output:
Enter the following values for rectangle:
Zength: integer value: 50
Breadth : integer value: 30
Area of rectangle is 1500
Let us tty to understand the above code. Every Python module has a built-in variable called
fame. (two underscores placed before and after ‘name’) containing the name of the moc lk.
When the module itself is being run as the script, this variable __name__ i pee
-main_’ designating it to be a__main__ module, Seema cnc’ the strie
Python checks whether the name of the
ree -Main__. This bein,
current module i
e and the fu ia ig true, the expression
‘unction main() gets executed,
im
the cling main) intone oe eCanRl Bets calle!
ere it gets displayed
As the main() gets executed, the anguy
the user and call to function areaRecta
inside this function and returns back
Itis to be remembered tha
t a functi
any other user-defined function °° Ot execute und it 's invoked,
i ‘ed, whether it is main() of
a Computer Science wit Pytron-!!
Pie
2.t
Exe
‘im
ap
on
bo
an
cal
sti
I“4 ty
™aing
ted by
ng
_ == Functions
2.8 FLOW OF EXECUTION oF pp
0
Execution always begins at th,
e fi
time, starting from the top to the ne t*ement of th
the botto, the program. State
a program, as the statement ing eo Neon ey tements are executed one at a
On a function call, instead of
: BOing to th
body of the function, executes a es
; oa ‘ement of the progr:
ba ee gram, the control jumps to the
and then comes back to the poin ine
i function, st
and then ae here ie tone me ae oon the top to the bottom
ther function, Sin «it left off. This remains imple till a function does not
'y in the midal
Setanta. D6 Other finction ang soon,” 3 {Retion, the program might have to execute
However, Python is good at keen,
pin,
the program Dicks up from qe o® HACK oF the execution a
ma the place where it jet cere 8 30 that each time a function completes
Fw
it terminates. For example, intil it gets to the end of the program where
1. defadd(a,b):
2 c=atb
3. return c
4, def sub(a,b):
5. if(a>b):
Geeec=a—b
7. else
Gc =b-a
us return c
10.
11.
12. X= 20
13. Y=10
14. Z=add(X,Y)
15. print(Z)
16. i = sub(X,Y)
17. print(i)
Upon execution of the above code, the flow of execution will be:
13 4> 12 > 13 > 14 > 125314515 516 5455 46 57-3839316 517
However, the flow of execution in case of both the functions shall be:
© goto line 1» 2-3 > 14> 15: for add(ab)
© goto line 5 > 6 > 7 +8 +9 > 10 > 16 > 17: for sub(a,b)
Explanation:
1. Execution begins from Statement 1. Here, interpreter encounters a function definition, which
will not be executed till the function is called.
2. Then the interpreter’s control reaches Statement 4, where the second function definition is
encountered which gets skipped.Yr.
uted:
preter Oz and 3. Statemen, ect
ere it Was Calley SS
rent 14 ero
s¢ again a function ca) a
ich is 284" al
whith g, 7, 8 and 9 respective, Ae
ei: Statement j;
tc wna finally executes rement ty aa
tis a function cally
i ing Ianguage: cw
Eau + powerful tots in P ng AEs ofiesell- I other wort
recursion sone of he owe ast sting ees
Rec _
Saw .eton cals itself one OF MOTE
itis
mn Pe
Conditions for Implementing Rectsio venice wantto so" Reirecursio
ition for the probl
for that problem.
itine, This
minating COM
led the base case
the recursive rou
eee ifclause specifies the terminatin,
2. There must be an if condition in
condition of the recursion.
the order of execution is
An
| 4, There must be a tel
wery recursive problem, is thi
is the characteristic of e
ive function calls are ni = BX
ution, the recurs!
| 3, Reversal it
I when a recursive program is taken for exec : F
| anereed immediately. They are pushed onto stack as long as the terminating condition js a
| ‘encountered. As soon as the recursive condition is encountered, the recursive calls which a
| twere pushed onto stack are removed in reverse order'and executed one by one, It means tha
| | the ast eall made will execute first, then the second-last call will execute and so on until th:
j | stack is empty.
|
4, Each tim is
i pe nea call is made, a new memory space is allocated to each loci ‘
} variable used by the recursive routine. In oth¢ i i
| vee ee oa AED words, during each recursive call to recursive 4
5 ursive Functi
jury ee ction gets a different set of values, but with 0
| 5. The duplicated values
ofthe local variables of a
H r
its respective cal and all thse vales are avalable at ee eect i
pene (orion atk. e to the respective function call when it
Disa ;
: aaeaet of using Recursion I
|. Itconsumes more stora,
5
Sita Be space because the recursive calls along with | i
local variables are stored :
1
ire not checked, 1
t
t
Computer Science with Pythor-M
eeVeay
ney
Meg
Cal,
Vely
th
ion,
ting
ile,
not
nis
dich
shat
the
deal
sive
vith
eee
How Recursion Works - |
Recursion is implemented p)
a Y dividi
function usually consists of the follow se Pecursive problem into
Terminating part (for the sy, wie Parts two parts, A useful recursive
directly. as
@ Recursive part which contains one
o
Let us write a recursive function
function, let us understand the a,
X= XOX*X"X....."X n times
OR
X= X*(X"X"X.....X*X) n-1 times
If we know the value of xv,
OR
XP = X* (X*(X*X...X*X) n-2 times
Tie know the value of X*2, we can calculate X* and,
XP=X(K(Keaet=2))
And this process will continue until the i
innermost expression becomes X"
the recursive function for X®,
Possible
Problem) when the function returns a value
© function. Before writing the recursive
‘olve this problem,
we can easily calculate X*
thus, calculate X*
Now, itis easy to write
Example 10: To calculate power of a number using recursion.
emmmemmnieneisec et Using recurs
#70 calculate power of a number using recursion
def power (x,n):
ifn == 0:
xeturn 4
else:
return x * power (x, n-1)
anz
print (power(a, 4))
Output:
16
Explanation:
In each call, the power() function passes the actual parameters to the version being called. The
i the value of n is decremented by 1 for each
value of is same foreach power ee function power) sat returning ae x
Pete eic ot rowert if nation is passed back to the previous version that made this call and this
Pee, occa iu re will continue until the value of the power can be passed to the origin]
ian eae erincion recursively, then there must exist such condition that is responsible
call. When we define a
for its termination.
_—
Functions
———————————el
the loop shall exe
on call is made re
‘Ursively With thi
h is the fibonace
‘he base condition on the basts of wh
i
equal to 1. Otherwise, the function ean
1 added to the function called re, 7
Finally, the returned value whic}
ae defined as the number less than or
fabs h the argument as the number minus
‘Sument as the number minus 2.
i seri
practical Implementation-19 s printed using a for loop.
Write a Recursive function to calculate
the Factorial of a number
else: |
seturn 2 * recur tactoriai (n-1)
num = int (input ("Enter a number
ig num < 0: a)
print("Sorry, factori,
vs Bt For A neckties Number, doen, not exist")
print ("The factorial of o is i»)
else:
print ("the factorial of”, num,
} Recur_factoriai (num) )
Case 2: fenter a number ]
The factorial of 10 is
Case3: fentez a number
Case 4:
Enter a number
Sorry, factorial for a negative number does not exist
att el
Practical Implementation-20 (Binary Search in lists/arrays)
Write a Recursive program to implement binary search in arrays/lists.
In binary search technique, the entire sequence of numbers (list/array) is divided into two parts
and the middle element of list/array is extracted. This technique is also known as divide and
conquer technique. fo search an element, say ‘val’ in a sorted array (suppose in ascending order),
the val is compared with the middle element first. If the searched value is equal to the middle
value, then the index number and position number of this element is returned. If the val is greater
than the middle element, the second half of the array becomes the new segment to be traversed;
if the val is less than the middle element, the first half becomes the new segment to be scanned.
The same process is repeated until val is found or the segment is reduced to the single element
and still val is not found (in case of an unsuccessful search).
or in this half
Either in this half
Ty al evvy
Se
«s fsearehed value is 42
«If searched value 18 30,
inary Search
if banary_ search (11257
sequigh < 220):
laa tow) // 2) ive
ase: nigh = at val
. tara = 100 2 (OEty mtaale mo
1 compare the search
+ = 4, val)
te Ligttnterall 7 Mehran ist, ows sieved =
ene aistimtavall © Wei ciist, midvar + 2, bagi
return Dinary_+
oo geurn mbaval
oe
ton, va):
vvvVv
v
v
2011
Mat = (5, 11, 22) 26, 99, 2081
(inary search (sist, 0
Print oinaryosenren ist, 0, 6, 400))
Output:
Lee |
Tone
2.9.1 Recursion vs Iteration
Recursion and iteration are inter-related concepts. However, even for problems that can be handle
aually wel using both the techniques, there isa subtle difference in the manner loops and metho
calls are handled by a programming language compiler,
When a loop is executed repeatedly, it uses the
MEME YEVONINE
Same memory locations for variables and repeats
the same unit of code. On the other hand, recursion, instead of repeating the same unit of code and
using the same memory locations for variables, allocates fresh memory space for each recursive cal
jerefore, we can say that any problem that can be solved through iteration can be solved usi
adaitong as Welland vice versa. But the limitation in case of recursion is that it involves a.
the at terms ofthe space used in RAM by each Tecursive call to a function ra, Pia
ee we
used by the function call,
Tecursive functions often
the same time, in certain
Computer Science with pytnon-Xi =m)Eas
MeNts that can
> Python can have three types of functions, ane
+ Built-in functions, se
+ Functions in modules, and
+ User-defined functions
> APython module can contain obj
ects ike docstrings, variables,
> APython module has the py extencon » Constants, classes, objects, statements, functions
» APython module can be imported in a
{i)_ import
(il) from import
he built-in functi
>T in lons of Python are always available; one need Not import any module fc
> The math module of Python provides math functionality na erat
> Functions make program handling eas
ling easier as only a
erat: Snlva small part of the programs dealt with ata time, thereby avoiding
> Afunction may or may not return a value.
> Avold function internally returns legal empty value None.
> eosin parts In which a particular piece of code or adata value (e.g, variable) can be accessed is known as
> In Python, broadly, scopes can either be global scope or local scope.
> Alocal variable having the same name as that of a global variable hides the global variable in its function,
> Afile that contains a collection of related functions grouped together and other definitions fs called module.
> Assearch path is the list of directories that the interpreter searches before importing a module.
> Alibrary is just a module that contains some useful definitions.
> The random() function generates a floating point random value from 0 to <1.
> A function is said to be recursive if it cals itself.
> There are two cases in each recursive function—the recursive case and the base case.
> An infinite recursion is when a recursive function calls itself endlessly.
> If there is no base case or if the base case is never executed, infinite recursion occurs.
> Iteration uses the same memory space for each pass contrary to recursion where fresh memory is allocated for each
Successive call,
> Recursive functions are relatively slower than their iterative counterparts,
> Somi nly used recursive algorithms are factorial, greatest common divisor, fibonacci series printing, binary
1e commor
Search, etc.
> String can be passed to a function as argument but it Is used as pass by value.
ina function.
euiace caret ba eutied ‘onary can be passed as an argument to a function like other variables
> In Python, everything is an object, so the dicti
are passed. @
SC, LS 2B