[go: up one dir, main page]

0% found this document useful (0 votes)
11 views24 pages

String Manipulation

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 24

The above program is same as the program we had written for ‘break’ statement except

that we have replaced it with ‘continue’. As you can see in the output except the letter ‘e’ all the
other letters get printed.

(iii) pass statement


pass statement in Python programming is a null statement. pass statement when
executed by the interpreter it is completely ignored. Nothing happens when pass is executed,
it results in no operation.

pass statement can be used in ‘if ’ clause as well as within loop construct, when you do
not want any statements or commands within that block to be executed.

Syntax:
pass

Example 6.17: Program to illustrate the use of pass statement


a=int (input(“Enter any number :”))
if (a==0):
pass
else:
print (“non zero value is accepted”)

Output:
Enter any number :3
non zero value is accepted
When the above code is executed if the input value is 0 (zero)
then no action will be performed, for all the other input values the
output will be as follows:

Note
pass statement is generally used as a placeholder. When we have a loop or function
that is to be implemented in the future and not now, we cannot develop such functions
or loops with empty body segment because the interpreter would raise an error. So, to
avoid this we can use pass statement to construct a body that does nothing.

XII Std Computer Science 84

12th Computer Science_EM Chapter 6.indd 84 26-12-2022 16:44:46


Example 6.18: Program to illustrate the use of pass statement in for loop
for val in “Computer”:
pass
print (“End of the loop, loop structure will be built in future”)

Output:
End of the loop, loop structure will be built in future.

Points to remember:

• Programs consists of statements which are executed in sequence, to alter the


flow we use control statements.
• A program statement that causes a jump of control from one part of the
program to another is called control structure or control statement.
• Three types of flow of control are
o Sequencing
o Branching or Alternative
o Iteration
• In Python, branching is done using various forms of ‘if ’ structures.
• Indentation plays a vital role in Python programming, it is the indentation
that group statements no need to use {}.
• Python Interpreter will throw error for all indentation errors.
• To accept input at runtime, earlier versions of Python supported raw_input(),
latest versions support input().
• print() supports the use of escape sequence to format the output to the user’s
choice.
• range() is used to supply a range of values in for loop.
• break, continue, pass act as jump statements in Python.
• pass statement is a null statement, it is generally used as a place holder.

85 Control Structures

12th Computer Science_EM Chapter 6.indd 85 26-12-2022 16:44:46


Hands on Experience

1. Write a program to check whether the given character is a vowel or not.

2. Using if..else..elif statement check smallest of three numbers.

3. Write a program to check if a number is Positive, Negative or zero.

4. Write a program to display Fibonacci series 0 1 1 2 3 4 5…… (upto n terms)


5. Write a program to display sum of natural numbers, upto n.
6. Write a program to check if the given number is a palindrome or not.
7. Write a program to print the following pattern
* * * * *
* * * *
* * *
* *
*
8. Write a program to check if the year is leap year or not.

Evaluation

Part - I

Choose the best answer 1 Marks


1. How many important control structures are there in Python?
A) 3 B) 4
C) 5 D) 6
2. elif can be considered to be abbreviation of
A) nested if B) if..else
C) else if D) if..elif
3. What plays a vital role in Python programming?
A) Statements B) Control
C) Structure D) Indentation
4. Which statement is generally used as a placeholder?
A) continue B) break
C) pass D) goto

XII Std Computer Science 86

12th Computer Science_EM Chapter 6.indd 86 26-12-2022 16:44:46


5. The condition in the if statement should be in the form of
A) Arithmetic or Relational expression
B) Arithmetic or Logical expression
C) Relational or Logical expression
D) Arithmetic
6. Which of the following is known as definite loop?
A) do..while B) while
C) for D) if..elif
7. What is the output of the following snippet?
i=1
while True:
if i%3 ==0:
break
print(i,end=' ')
i +=1
A) 12 B) 123
C) 1234 D) 124
8. What is the output of the following snippet?
T=1
while T:
print(True)
break
A) False B) True
C) 0 D) 1
9. Which amongst this is not a jump statement ?
A) for B) pass
C) continue D) break
10. Which punctuation should be used in the blank?
if <condition>_
statements-block 1
else:
statements-block 2
A) ; B) :
C) :: D) !
87 Control Structures

12th Computer Science_EM Chapter 6.indd 87 26-12-2022 16:44:46


Part -II

Answer the following questions 2 Marks


1. List the control structures in Python.
2. Write note on break statement.
3. Write is the syntax of if..else statement
4. Define control structure.
5. Write note on range () in loop

Part -III

Answer the following questions 3 Marks


1. Write a program to display
A
A B
A B C
A B C D
A B C D E
2. Write note on if..else structure.
3. Using if..else..elif statement write a suitable program to display largest of 3 numbers.
4. Write the syntax of while loop.
5. List the differences between break and continue statements.

Part -IV

Answer the following questions 5 Marks


1. Write a detail note on for loop
2. Write a detail note on if..else..elif statement with suitable example.
3. Write a program to display all 3 digit odd numbers.
4. Write a program to display multiplication table for a given number.

XII Std Computer Science 88

12th Computer Science_EM Chapter 6.indd 88 26-12-2022 16:44:46


CHAPTER 7
Unit II
PYTHON FUNCTIONS

Main advantages of functions are


Learning Objectives
• It avoids repetition and makes high degree
of code reusing.
After studying this chapter, students will be
able to: • It provides better modularity for your
application.
• Understand the concept of function and
their types.
Note
• Know the difference between User Functions are nothing but a group
defined and Built in functions. of related statements that perform a
• Know how to call a function. specific task.

• Understand the function arguments. 7.1.1 Types of Functions

• Know Anonymous functions. Basically, we can divide functions


into the following types:
• Know Mathematical and some String
functions. 1 User-defined Functions
2 Built-in Functions
7.1 Introduction Lambda Functions
3
Recursion Functions
Functions are named blocks of code 4

that are designed to do specific job. When


Figure – 7.1 – Types of Python Functions
you want to perform a particular task that
you have defined in a function, you call
Functions Description
the name of the function responsible for it.
If you need to perform that task multiple User-defined Functions defined by
times throughout your program, you don’t functions the users themselves.
need to type all the code for the same task Built-in Functions that are
again and again; you just call the function functions inbuilt with in Python.
dedicated to handling that task, and the Lambda Functions that are
call tells Python to run the code inside the functions anonymous un-named
function. You’ll find that using functions function.
makes your programs easier to write, read,
test, and fix errors.
89

12th Computer Science_EM Chapter 7.indd 89 21-12-2022 15:21:23


• If any input parameters are present should
Recursion Functions that calls
functions itself is known as be placed within these parentheses when
recursive. you define a function.

Table – 7.1 – Python Functions and it's • The code block always comes after a
Description colon (:) and is indented.

Defining Functions • The statement “return [expression]”


7.2
exits a function, optionally passing back
Functions must be defined, to create an expression to the caller. A “return”
and use certain functionality. There are with no arguments is the same as return
many built-in functions that comes with the None.
language python (for instance, the print()
function), but you can also define your own Note
function. When defining functions there are Python keywords should not be used
multiple things that need to be noted; as function name.
• Function blocks begin with the keyword
“def ” followed by function name and
parenthesis ().

7.2.1 Syntax for User defined function

def <function_name ([parameter1, parameter2…] )> : Note


<Block of Statements> In the above Syntax, the Text
return <expression / None> which is given in square
bracket [] is optional.

Block: Nested Block:


A block is one or more lines of A block within a block is called
code, grouped together so that they nested block. When the first block
are treated as one big sequence of statement is indented by a single tab
statements while execution. In Python, space, the second block of statement is
statements in a block are written with indented by double tab spaces.
indentation. Usually, a block begins
when a line is indented (by four Here is an example of defining a function;
spaces) and all the statements of the
def Do_Something( ):
block should be at same indent level.
value =1 #Assignment Statement
return value #Return Statement

XII Std Computer Science 90

12th Computer Science_EM Chapter 7.indd 90 21-12-2022 15:21:23


Now let’s check out functions in action so you can visually see how they work within a
program. Here is an example for a simple function to display the given string.
Example: 7.2.1
def hello():
print (“hello - Python”)
return

7.2.2 Advantages of User-defined Functions


1. Functions help us to divide a program into modules. This makes the code easier to
manage.
2. It implements code reuse. Every time you need to execute a sequence of statements, all
you need to do is to call the function.
3. Functions, allows us to change functionality easily, and different programmers can work
on different functions.
7.3 Calling a Function
To call the hello() function from example 7.2-1, use the following code:
Example: 7.3.1
def hello():
print (“hello - Python”)
return
(hello()

When you call the “hello()” function, the program displays the following string as
output:
Output
hello – Python

Alternatively we can call the “hello()” function within the print() function as in the
example given below.
Example: 7.3.2
def hello():
print (“hello - Python”)
return
print (hello())

If the return has no argument, “None” will be displayed as the last statement of the
output.

91 Python Functions

12th Computer Science_EM Chapter 7.indd 91 21-12-2022 15:21:23


The above function will output the following.

Output:
hello – Python
None

7.4 Passing Parameters in Functions

Parameters can be declared to functions

Syntax:
def function_name (parameter(s) separated by comma):

Let us see the use of parameters while defining functions. The parameters that you
place in the parenthesis will be used by the function itself. You can pass all sorts of data to the
functions. Here is an example program that defines a function that helps to pass parameters
into the function.
Example: 7.4
# assume w = 3 and h = 5
def area(w,h):
return w * h
print (area (3,5))

The above code assigns the width and height values to the parameters w and h. These
parameters are used in the creation of the function “area”. When you call the above function,
it returns the product of width and height as output.
The value of 3 and 5 are passed to w and h respectively, the function will return 15 as
output.

We often use the terms parameters and arguments interchangeably. However, there
is a slight difference between them. Parameters are the variables used in the function
definition whereas arguments are the values we pass to the function parameters

7.5 Function Arguments

Arguments are used to call a function and there are primarily 4 types of functions that
one can use: Required arguments, Keyword arguments, Default arguments and Variable-length
arguments.

XII Std Computer Science 92

12th Computer Science_EM Chapter 7.indd 92 21-12-2022 15:21:23


Function Arguments

1 Required arguments

2 Keyword arguments

3 Default arguments

4 Variable-length arguments

7.5.1 Required Arguments


“Required Arguments” are the arguments passed to a function in correct positional
order. Here, the number of arguments in the function call should match exactly with the
function definition. You need atleast one parameter to prevent syntax errors to get the required
output.
Example :7.5.1
def printstring(str):
print ("Example - Required arguments ")
print (str)
return
# Now you can call printstring() function
printstring()

When the above code is executed, it produces the following error.


Traceback (most recent call last):
File "Req-arg.py", line 10, in <module>
printstring()
TypeError: printstring() missing 1 required positional argument: 'str'

Instead of printstring() in the above code if we use printstring (“Welcome”) then the
output is

Output:
Example - Required arguments
Welcome

93 Python Functions

12th Computer Science_EM Chapter 7.indd 93 21-12-2022 15:21:23


7.5.2 Keyword Arguments
Keyword arguments will invoke the function after the parameters are recognized by
their parameter names. The value of the keyword argument is matched with the parameter
name and so, one can also put arguments in improper order (not in order).
Example: 7.5.2 (a)
def printdata (name):
print (“Example-1 Keyword arguments”)
print (“Name :”,name)
return
# Now you can call printdata() function
printdata(name = “Gshan”)

When the above code is executed, it produces the following output :

Output:
Example-1 Keyword arguments
Name :Gshan

Example: 7.5.2 (b)


def printdata (name):
print (“Example-2 Keyword arguments”)
print (“Name :”, name)
return
# Now you can call printdata() function
printdata (name1 = “Gshan”)

When the above code is executed, it produces the following result :

TypeError: printdata() got an unexpected keyword argument 'name1'

Example: 7.5.2 (c)


def printdata (name, age):
print ("Example-3 Keyword arguments")
print ("Name :",name)
print ("Age :",age)
return
# Now you can call printdata() function
printdata (age=25, name="Gshan")

XII Std Computer Science 94

12th Computer Science_EM Chapter 7.indd 94 21-12-2022 15:21:23


When the above code is executed, it produces the following result:

Output:
Example-3 Keyword arguments
Name : Gshan
Age : 25

Note
In the above program the parameters orders are changed

7.5.3 Default Arguments


In Python the default argument is an argument that takes a default value if no value
is provided in the function call. The following example uses default arguments, that prints
default salary when no argument is passed.

Example: 7.5.3
def printinfo( name, salary = 3500):
print (“Name: “, name)
print (“Salary: “, salary)
return
printinfo(“Mani”)

When the above code is executed, it produces the following output

Output:
Name: Mani
Salary: 3500

When the above code is changed as printinfo(“Ram”,2000) it produces the following


output:

Output:
Name: Ram
Salary: 2000

In the above code, the value 2000 is passed to the argument salary, the default value
already assigned for salary is simply ignored.

95 Python Functions

12th Computer Science_EM Chapter 7.indd 95 21-12-2022 15:21:23


7.5.4 Variable-Length Arguments
In some instances you might need to pass more arguments than have already been
specified. Going back to the function to redefine it can be a tedious process. Variable-Length
arguments can be used instead. These are not specified in the function’s definition and an
asterisk (*) is used to define such arguments.
Lets see what happens when we pass more than 3 arguments in the sum() function.

Example: 7.5.4
def sum(x,y,z):
print("sum of three nos :",x+y+z)
sum(5,10,15,20,25)

When the above code is executed, it produces the following result :

TypeError: sum() takes 3 positional arguments but 5 were given

7.5.4.1 Syntax - Variable-Length Arguments


def function_name(*args):
function_body
return_statement

Example: 7.5.4. 1
def printnos (*nos): Output:
for n in nos: Printing two values
print(n) 1
return 2
# now invoking the printnos() function Printing three values
print ('Printing two values') 10
printnos (1,2) 20
print ('Printing three values') 30
printnos (10,20,30)

Evaluate Yourself ?

In the above program change the function name printnos as printnames in all places
wherever it is used and give the appropriate data Ex. printnos (10, 20, 30) as printnames ('mala',
'kala', 'bala') and see output.

XII Std Computer Science 96

12th Computer Science_EM Chapter 7.indd 96 21-12-2022 15:21:24


In Variable Length arguments we can pass the arguments using two methods.
1. Non keyword variable arguments
2. Keyword variable arguments
Non-keyword variable arguments are called tuples. You will learn more about tuples in
the later chapters. The Program given is an illustration for non keyword variable argument.

Note
Keyword variable arguments are beyond the scope of this book.

The Python’s print() function is itself an example of such a function which


supports variable length arguments.

7.6 Anonymous Functions

What is anonymous function?


In Python, anonymous function is a function that is defined without a name. While
normal functions are defined using the def keyword, in Python anonymous functions are
defined using the lambda keyword. Hence, anonymous functions are also called as lambda
functions.

What is the use of lambda or anonymous function?


• Lambda function is mostly used for creating small and one-time anonymous function.
• Lambda functions are mainly used in combination with the functions like filter(), map()
and reduce().

Note
filter(), map() and reduce() functions are beyond the scope of this book.

Lambda function can take any number of arguments and must return one
value in the form of an expression. Lambda function can only access global variables
and variables in its parameter list.

97 Python Functions

12th Computer Science_EM Chapter 7.indd 97 21-12-2022 15:21:24


7.6.1 Syntax of Anonymous Functions
The syntax for anonymous functions is as follows:

lambda [argument(s)] :expression Example: 7.6.1


sum = lambda arg1, arg2: arg1 + arg2
print ('The Sum is :', sum(30,40))
print ('The Sum is :', sum(-30,40))
Output:
The Sum is : 70
The Sum is : 10

The above lambda function that adds argument arg1 with argument arg2 and stores the
result in the variable sum. The result is displayed using the print().

7.7 The return Statement

• The return statement causes your function to exit and returns a value to its caller. The
point of functions in general is to take inputs and return something.
• The return statement is used when a function is ready to return a value to its caller. So,
only one return statement is executed at run time even though the function contains
multiple return statements.
• Any number of 'return' statements are allowed in a function definition but only one of
them is executed at run time.
7.7.1 Syntax of return

return [expression list ]

This statement can contain expression which gets evaluated and the value is returned.
If there is no expression in the statement or the return statement itself is not present inside a
function, then the function will return the None object.

XII Std Computer Science 98

12th Computer Science_EM Chapter 7.indd 98 21-12-2022 15:21:24


Example : 7.7.1
# return statment
def usr_abs (n):
if n>=0:
return n
else:
return –n
# Now invoking the function
x=int (input(“Enter a number :”)
print (usr_abs (x))
Output 1:
Enter a number : 25
25
Output 2:
Enter a number : -25
25

7.8 Scope of Variables


Scope of variable refers to the part of the program, where it is accessible, i.e., 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 scopes - local scope and global scope.

7.8.1 Local Scope


A variable declared inside the function's body is known as local variable.
Rules of local variable
• A variable with local scope can be accessed only within the function that it is created in.
• When a variable is created inside the function the variable becomes local to it.
• A local variable only exists while the function is executing.
• The formal parameters are also local to function.

99 Python Functions

12th Computer Science_EM Chapter 7.indd 99 21-12-2022 15:21:24


Example : 7.8.1 (a) Create a Local Variable
def loc():
y=0 # local scope
print(y)
loc()
Output:
0

Example : 7.8.1 (b)Accessing local variable outside the scope


def loc():
y = "local"
loc()
print(y)

When we run the above code, the output shows the following error:
The above error occurs because we are trying to access a local variable ‘y’ in a global
scope.

NameError: name 'y' is not defined

7.8.2 Global Scope


A variable, with global scope can be used anywhere in the program. It can be created by
defining a variable outside the scope of any function.
Rules of global Keyword
The basic rules for global keyword in Python are:
• When we define a variable outside a function, it’s global by default. You don’t have to use
global keyword.
• We use global keyword to modify the value of the global variable inside a function.
• Use of global keyword outside a function has no effect
Use of global Keyword
Example : 7.8.2 (a) Accessing global Variable From Inside a Function
c = 1 # global variable
def add():
print(c)
add()
Output:
1

XII Std Computer Science 100

12th Computer Science_EM Chapter 7.indd 100 21-12-2022 15:21:24


Example : 7.8.2 (b) Modifying Global Variable From Inside the Function
c = 1 # global variable
def add():
c = c + 2 # increment c by 2
print(c)
add()
Output:
UnboundLocal Error: local variable 'c' referenced before assignment

Note
Without using the global keyword we cannot modify the global variable inside
the function but we can only access the global variable.

Example : 7.8.2(c) C hanging Global Variable From Inside a Function


using global keyword
x = 0 # global variable
def add():
global x
x = x + 5 # increment by 5
print ("Inside add() function x value is :", x)
add()
print ("In main x value is :", x)
Output:
Inside add() function x value is : 5
In main x value is : 5

In the above program, x is defined as a global variable. Inside the add() function, global
keyword is used for x and we increment the variable x by 5. Now We can see the change on the
global variable x outside the function i.e the value of x is 5.

101 Python Functions

12th Computer Science_EM Chapter 7.indd 101 21-12-2022 15:21:24


7.8.3 Global and local variables
Here, we will show how to use global variables and local variables in the same code.
Example : 7.8.3 (a) Using Global and Local variables in same code
x=8 # x is a global variable
def loc():
global x
y = "local"
x=x*2
print(x)
print(y)
loc()
Output:
16
local

In the above program, we declare x as global and y as local variable in the function
loc().
After calling the function loc(), the value of x becomes 16 because we used x=x * 2.
After that, we print the value of local variable y i.e. local.

Example : 7.8.3 (b) Global variable and Local variable with same name

x=5
def loc():
x = 10
print ("local x:", x)
loc()
print ("global x:", x)

Output:
local x: 10
global x: 5

In above code, we used same name ‘x’ for both global variable and local variable. We get
different result when we print same variable because the variable is declared in both scopes, i.e.
the local scope inside the function loc() and global scope outside the function loc().
The output :- local x: 10, is called local scope of variable.
The output:- global x: 5, is called global scope of variable.

XII Std Computer Science 102

12th Computer Science_EM Chapter 7.indd 102 21-12-2022 15:21:24


7.9 Functions using libraries
7.9.1 Built-in and Mathematical functions

Function Description Syntax Example


abs ( ) Returns an x=20
absolute value y=-23.2
of a number. print('x = ', abs(x))
The argument
print('y = ', abs(y))
may be an abs (x)
integer or a Output:
floating point
x = 20
n u m b e r.
y = 23.2
ord ( ) Returns the c= 'a'
ASCII value d= 'A'
for the given print ('c = ',ord (c))
Unicode ord (c) print ('A = ',ord (d))
character.
This function is Output:
inverse of chr() c = 97
function. A = 65
chr ( ) Returns the c=65
Unicode d=43
character for print (chr (c))
the given ASCII chr (i) prin t(chr (d))
value.
This function is Output:
inverse of ord() A
function. +
bin ( ) Returns a x=15
binary string y=101
prefixed with print ('15 in binary : ',bin (x))
“0b” for the print ('101 in binary : ',bin (y))
given integer bin (i)
number. Output:
Note: format 15 in binary : 0b1111
() can also be 101 in binary : 0b1100101
used instead of
this function.

103 Python Functions

12th Computer Science_EM Chapter 7.indd 103 21-12-2022 15:21:24


type ( ) Returns the x= 15.2
type of object y= 'a'
for the given s= True
single object. print (type (x))
Note: This type (object) print (type (y))
function print (type (s))
used with
single object Output:
parameter. <class 'float'>
<class 'str'>
<class 'bool'>
id ( ) id( ) Return x=15
the “identity” of y='a'
an object. i.e. print ('address of x is :',id (x))
the address of id (object) print ('address of y is :',id (y))
the object in
Output:
memory.
Note: the address of x is : 1357486752
address of x address of y is : 13480736
and y may
differ in your
system.
min ( ) Returns the MyList = [21,76,98,23]
minimum value print ('Minimum of MyList :', min(MyList))
in a list. min (list)
Output:
Minimum of MyList : 21
max ( ) Returns the MyList = [21,76,98,23]
maximum print ('Maximum of MyList :', max(MyList))
value in a list.
max (list) Output:
Maximum of MyList : 98
sum ( ) Returns the MyList = [21,76,98,23]
sum of values print ('Sum of MyList :', sum(MyList))
in a list. sum (list)
Output:
Sum of MyList : 218

XII Std Computer Science 104

12th Computer Science_EM Chapter 7.indd 104 21-12-2022 15:21:24


format ( ) Returns the x= 14
output based y= 25
on the given print ('x value in binary :',format(x,'b'))
format print ('y value in octal :',format(y,'o'))
1. Binary print('y value in Fixed-point no ',format(y,'f '))
format.
Outputs the format (value Output:
number in [, format_ x value in binary : 1110
base 2. spec]) y value in octal : 31
2. Octal y value in Fixed-point no : 25.000000
format.
Outputs the
number in
base 8.
3. Fixed-point
notation.
Displays the
number as a
fixed-point
number.
The default
precision
is 6.
round ( ) Returns the x= 17.9
nearest integer y= 22.2
to its input. z= -18.3
1. First print ('x value is rounded to', round (x))
argument round print ('y value is rounded to', round (y))
(number) (number print ('z value is rounded to', round (z))
is used to [,ndigits])
specify the
value to be
rounded.

105 Python Functions

12th Computer Science_EM Chapter 7.indd 105 21-12-2022 15:21:24


2. Second Output:1
argument x value is rounded to 18
(ndigits) y value is rounded to 22
is used to z value is rounded to -18
specify the n1=17.89
number print (round (n1,0))
of decimal print (round (n1,1))
digits print (round (n1,2))
desired after
rounding. Output:2
18.0
17.9
17.89
pow ( ) Returns the a= 5
computation of b= 2
ab i.e. (a**b ) c= 3.0
a raised to the print (pow (a,b))
power of b. print (pow (a,c))
pow (a,b) print (pow (a+b,3))

Output:
25
125.0
343

Mathematical Functions

Note
Specify import math module before using all mathematical
functions in a program

Function Description Syntax Example


floor ( ) Returns the largest integer math.floor (x) import math
less than or equal to x x=26.7
y=-26.7
z=-23.2
print (math.floor (x))
print (math.floor (y))
print (math.floor (z))
Output:
26
-27
-24

XII Std Computer Science 106

12th Computer Science_EM Chapter 7.indd 106 21-12-2022 15:21:24


ceil ( ) Returns the smallest math.ceil (x) import math
integer greater than or x= 26.7
equal to x y= -26.7
z= -23.2
print (math.ceil (x))
print (math.ceil (y))
print (math.ceil (z))
Output:
27
-26
-23
sqrt ( ) Returns the square root math.sqrt (x ) import math
of x a= 30
Note: x must be greater b= 49
than 0 (zero) c= 25.5
print (math.sqrt (a))
print (math.sqrt (b))
print (math.sqrt (c))
Output:
5.477225575051661
7.0
5.049752469181039
7.9.2 Composition in functions
What is Composition in functions?
The value returned by a function may be used as an argument for another function in
a nested manner. This is called composition. For example, if we wish to take a numeric value
or an expression as a input from the user, we take the input string from the user using the
function input() and apply eval() function to evaluate its value, for example:
Example : 7.9. 2
# This program explains composition
>>> n1 = eval (input ("Enter a number: "))
Enter a number: 234
>>> n1
234
>>> n2 = eval (input ("Enter an arithmetic expression: "))
Enter an arithmetic expression: 12.0+13.0 * 2
>>> n2
38.0

7.10 Python recursive functions


When a function calls itself is known as recursion. Recursion works like loop but
sometimes it makes more sense to use recursion than loop. You can convert any loop to

107 Python Functions

12th Computer Science_EM Chapter 7.indd 107 21-12-2022 15:21:24

You might also like