Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

Functions in Python

The document provides an overview of functions in Python, including definitions, types, and their significance in programming. It explains user-defined functions, their structure, flow of execution, and the difference between parameters and arguments. Additionally, it covers the scope of variables, including local and global variables, and their lifetimes.

Uploaded by

sarfrasisbah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Functions in Python

The document provides an overview of functions in Python, including definitions, types, and their significance in programming. It explains user-defined functions, their structure, flow of execution, and the difference between parameters and arguments. Additionally, it covers the scope of variables, including local and global variables, and their lifetimes.

Uploaded by

sarfrasisbah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

CLASS XII – COMPUTER SCIENCE (2025-26)

UNIT 1 – Computational Thinking and Programming - 2


Functions
Function Definition:
Function can be defined as a named group of instructions that are executed when the
function is invoked or called by its name.

 It contains statements, which are sequentially executed from top to bottom by python
Interpreter.
 Once defined, a function can be called repeatedly from different places of the program
without writing same code of that function every time, or it can be called from inside
another function, by simply writing the name of the function and passing the required
parameters, if any.

Significance/Advantages of using functions in a program:

 Increases readability, particularly for longer code as by using functions, the program is
better organized and easy to understand.
 Reduces code length as same code is not required to be written at multiple places in a
program. This also makes debugging easier.
 Increases reusability, as function can be called from another function or another program.
Thus, we can reuse or build upon already defined functions and avoid repetitions of
writing the same piece of code.
 Work can be easily divided among team members and completed in parallel.
Types of functions

Python functions are of three types:


1. Built-in functions: These functions are predefined in Python. E.g. len( ), type( ), input( )
etc.

2. Functions defined in modules: These functions are predefined in a particular module


and can be when the corresponding module is imported.
eg. import math
a=144
print(math.sqrt(a))

3. User defined functions: These are the functions defined by the programmer as per the
requirement.
Creating User defined function:
General format of User defined function:

<Function name>([arguments])  Function Call

Elements of a function:
i) Function header: The first line of a function definition that begins with the keyword def
and ends with a colon(:). It specifies the name of the function and its parameters, if any.

ii) Parameters: Parameters are the variable(s)/value(s) provided in the parenthesis when
we write function header. These are the values required by function to work.
eg. def Area(radius):
A=3.14*radius*radius
If there is more than one value required by the function to work on, then, all of them
will be listed in parameter list separated by comma.
iii) Function body: The block of indented statements beneath function header that defines
the action performed by the function. The function may or may not return a value.

iv) Function call: A function call is an expression containing the function name followed by
parenthesis, (). If the function has been defined to receive parameters, the values that are
to be sent into the function are listed inside the parentheses of the function call operator.

v) Arguments: Arguments are the value(s) provided in function call/invoke statement.

List of arguments should be supplied in same way as parameters are listed. Bounding of
parameters to arguments is done 1:1, and so there should be same number of arguments
as mentioned in parameter list.
Example of argument in function call
>>> area (5)
5 is an argument.
An argument can be literal, variable, or expression.

Some Important points to remember:


• The items enclosed in "()" in the function header are called parameters and they are
optional. Hence, a function may or may not have parameters.
• A function may or may not return a value.
• Function header always ends with a colon (:).
• Function name should be unique. Rules for naming identifiers also applies for
function naming.
• The statements outside the function indentation are not considered as part of the function

Flow of Execution:
Flow of Execution refers to the order in which statements are executed during program run.

When the interpreter encounters a function definition, the statements inside the function are
not executed until the function is called. Later, when the interpreter encounters a function
call, the control jumps to the called function and executes the statement of that function.
After that, the control comes back the point of function call so that the remaining statements
in the program can be executed..
Example:
1. Trace the flow of execution for the following programs:
1 def calsum(x , y ) :
2 z=x+y
3 return z
4
5 num1 = int(input (“Enter first number”))
6 num2 = int(input(“Enter second number”))
7 sum = calsum(num1, num2 )
8 print(“Sum of 2 numbers=”, sum

Flow of execution of the above code is:


5→6→7→1→2→3→7→8
2. Trace the flow of execution for the following programs:
1 def calsum(x , y ) :
2 z=x+y
3 return z
4
5 num1 = int(input (“Enter first number”))
6 num2 = int(input(“Enter second number”))
7 sum = calsum(num1, num2 )
8 print(“Sum of 2 numbers=”, sum
Flow of execution of the above code is:
5→6→7→1→2→3→7→8

Types of User defined functions:

Type 1: User defined function without arguments and without return value(void functions
without any arguments).
Eg.
def add( ):
A = int(input (“Enter first number”))
B = int(input(“Enter second number”))
C=A+B
print(“Sum of 2 numbers=”, C)
add( )
Type 2: User defined functions without arguments and with return value (fruitful
functions without any arguments)
Eg)
def add( ):
A = int(input (“Enter first number”))
B = int(input(“Enter second number”))
C=A+B
return C
Result = add()
print(“Sum of 2 numbers=”, Result)

Type 3: User defined functions with arguments and without return value (void functions
with some arguments)
Eg)
def add(a,b ) :
C=a+b
print(“Sum of 2 numbers=”, C)
X = int(input (“Enter first number”))
Y = int(input(“Enter second number”))
add(X, Y )

Type 4: User defined functions with arguments and with return value (fruitful
functions with some arguments)

E.g.
def add(a, b ) :
C=a+b
return C
X = int(input (“Enter first number”))
Y = int(input(“Enter second number”))
Result = add(X, Y)
print(“Sum of 2 numbers=”, Result)

Caller: The function calling another function is called the Caller. In the above example _main_
is the caller of add( ).

Called function / Callee: The function being called is the Called function. In the above
example add( ) is the called function.

Difference between arguments and parameters.


The values being passed through a function call statement are called arguments.
They are also known as actual arguments or actual parameters.

The values received in the function definition/function header are called parameters. They
are also known as formal arguments or formal parameters.
Eg;)
def add(a,b ) :
C=a+b
print(“Sum of 2 numbers=”, C)
X = int(input (“Enter first number”))
Y = int(input(“Enter second number”))
add(X, Y )

In this example a,b are parameters/ formal arguments / formal parameters


X,Y are arguments/ actual arguments /actual parameters.

Different types of parameters:


1) Positional paraments (Required arguments/Mandatory arguments)
2) Default parameters
1) Positional parameters:
In function call,
*The arguments must be provided for all parameters.
*The values of arguments are matched with parameters position wise.
(In a function call statement, when the number and order of arguments matches with function
definition, it is called positional argumenting or positional matching.)
Eg.)
If the function header is
def check(a, b, c):
if the function call is
check(x, y, z)
Then a will get value of x, b will get value of y, c will get value of z

2) Default arguments:
A parameter having default value in the function header is known as a default
parameter.
 The default values are specified in the function header of function definition.
 A default argument can be skipped in function call statement.
 The default values for parameters are considered only if no value is provided for that
parameter in the function call statement.

E.g., If the function header is


def interest(P, T, R =10):
If the function call is
SI = interest (5400,2) #Third argument is missing. Here P gets value of 5400,
#T gets value of 2 and R takes the default value 10
If the function call is
SI = interest(6100,3,15) #Here P gets value of 6100,T gets value of 3 and
#R gets value of 15
Rules to be followed while assigning default values to parameters:
The default parameters must be the trailing parameters in the function header that means if
any parameter is having default value then all the other parameters to its right must also have
default values.
E.g.
def interest(P, T, R =10): # legal
def interest(P , T=2, R): #illegal(Non default parameters cannot follow default parameter
def interest (P=2000,T=2, R): #illegal (Same reason given above)
def interest(P, T=2, R= 10): #legal
def interest (P=2000, T=2, R=10): #legal
Advantages of using default arguments:
 It can be useful in situations where some parameters always have the same value, so they
provide greater flexibility to the programmers.
 They can be used to add new parameters to the existing functions.
 They can be used to combine similar functions into one.

Function returning values:


The return statement returns the value from the function. A function may or may not return
a value when called.

The return statement does the following:


• returns the control to the calling function.
• return value(s) or None.

Category of functions based on return statement:


Based on whether a function has a return statement or not, functions are categorized into two
types:
i) non void functions or fruitful functions: These are functions returning some values.

ii) void functions or non-fruitful functions: These are functions not returning any values.

non-void functions / fruitful functions:

The functions that return some computed result in terms of a value is called non void
functions.
The computed value is returned using return statement. The value being returned can be
one of the following:
i) a literal
ii) a variable
iii) an expression
Eg)
return 5 # literal being returned
return 6+4 # an expression involving literals being returned
return a # variable being returned
return a**3 #expression involving variable and literal, being returned
return (a+8**2)/ b # expression involving variables and literal, being returned
return a+b/c # expression involving variables being returned

NOTE 1: The returned value of a function should be used in the caller function inside an
expression or a statement.
Eg)
def sum (x,y) :
S=x+y
return S
add_result = sum(3,5) # The returned value being used in assignment statement
print(sum(3,4)) # The returned value being used in print statement
sum(4,5) > 6 # The returned value being used in a relational expression

NOTE 2 : The return statement ends a function execution even if it is in the middle of the
function.
Eg)
import math
def check(a):
a = math.fabs(a)
return a
print (a) #This statement is unreachable because check( ) function will end
#with return and control will never reach this statement
check(-15)
NOTE 3: Returning multiple values.
In Python , a function may return multiple values. In multiple returning , it returns a
sequence of values to the calling statement.
To return multiple values from a function ,
i) The return statement inside a function body should be of the form:
return <value1/variable1/expression1> , <value1/variable1/expression1> , ………

ii)The function call statement should receive or use the returned values in one of the
following ways:

a) Either receive the returned value in form of a tuple variable


Eg)
def squared(x, y, z) :
return x*x, y*y , z*z #The return statement returning comma separated multiple values
t =squared(2,3,4) #variable t receives the returned values as a tuple
print(t) #tuple t will be printed as (4,9,16)
b) Directly unpack the received values of tuple by specifying the same number of
variables on the left hand side of the assignment in function call.
Eg)
def squared (x, y, z):
return x*x , y*y, z*z
v1 , v2, v3 =squared( 2 , 3, 4) #The received values are in the form of three different variables
print(v1 , v2, v3

Void functions / non-fruitful functions:


The functions that perform some action but do not return any computed value to the caller
are called void functions.
 A void function may or may not have a return statement. If a void function has a return
statement, then it takes the following form:

return
Eg)
#void function but no return statement #void function with a return statement
def greet( ): def quote ( ):
print(“helloz”) print(“Goodness counts!!”)
return

def greet1(name): def prinsum(a, b, c) :


print(“Hello”, name) print(“Sum is” , a+b+c)
return

 The void functions are generally not used inside a statement or expression in the caller;
their function call statement is standalone complete statement itself.
Eg)
greet( )
greet1(NAM)
quote( )
prinsum(4,6,9)

 Every void function returns value None to its caller.


Eg)
def greet( ): def replicate( ) : def replicate1( ) :
print(“Helloz”) print(“$$$$”) return “$$$$”
a= greet( ) print(replicate( )) print(replicate1( ))
print(a )

o/p: o/p: o/p:


Helloz $$$$ $$$$
None None
Scope of variables:
Part(s) of program within which a name is legal and accessible, is called scope of the name.

Types of scopes in Python:


Python supports two types of scope. They are:
i) Global scope
ii) Local scope
Global Scope: A name declared in top level segment ( main ) of a program is said to have a
global scope and is usable inside the whole program and all blocks(functions, other blocks)
contained within the program.

Local Scope: A name declared in a function-body is said to have local scope i.e. it can be used
only within this function and the other blocks container under it.
Lifetime of a variable:
The time for which a variable remains in memory is called Lifetime of a variable.
Differentiate between Local variable and Global variable.

Local Variable Global Variable


A variable that is defined inside any A variable that is defined outside any
function or a block is known as a local function or any block is known as global
variable. variable.
It can be accessed only in the function or a It can be accessed throughout the python
block where it is defined. code
Any change made to the local variable will Any change made to the global variable
not impact all the functions in the program will impact all the functions in the
where that variable can be accessed. program where that variable can be
accessed.
Life time of a local variable is their Life time of a global variable is entire
function’s run program run

A local variable has local scope A global variable has global scope

E.g. E.g.
def calsum(x , y ) : def calsum(x , y ) :
z=x+y z=x+y
return z return z
num1 = int(input (“Enter first number”)) num1 = int(input (“Enter first number”))
num2 = int(input(“Enter second number”)) num2 = int(input(“Enter second number”))
sum = calsum(num1, num2 ) sum = calsum(num1, num2 )
print(“Sum of 2 numbers=”, sum) print(“Sum of 2 numbers=”, sum)

Local variables are x, y, z Global variables are num1,num2 ,sum


Same variable name in local scope as well as in global scope:
E.g.
def state1( ) :
tigers = 15 #This statement will create a local variable with name tigers. It won’t
print(tigers) # refer to tigers of main program
tigers = 95
print(tigers)
state1( )
print(tigers)
o/p:
95
15
95

NOTE: When a local variable is created with same name as that of global variable, it hides
the global variable in function definition.

To use a global variable inside local scope when the same variable name is having local scope
as well as global scope, the keyword global should be prefixed before the variable.

Syntax:
global < variable name>

E.g.
def state1( ) :
global tigers #This is an indication that not to create local variable with the name tigers
tigers = 15 #rather use global variable tigers
print(tigers)
tigers = 95
print(tigers)
state1( )
print(tigers)
o/p:
95
15
15

NOTE:
1) Once a variable is declared global in a function, you cannot undo the statement (ie, after
a global statement, the function will always refer to the global variable and local variable
cannot be created by the same name).
2) Although global variables can be accessed through local scope, but it is not a good
programming practice, So keep global variables global and local variables local.
Passing immutable arguments and mutable arguments in function call:
1) Passing immutable arguments in function call.

When immutable type arguments (eg. Numbers, strings etc.) are passed in a function call
then any change in its value will also change the memory address it is referring to. So after
returning from the function definition the originally passed variable remains unchanged.

E.g.
def change(x):
x+=5
print("Change made in function: ",x)
a=10
print("Value of a before function call: ",a)
change(a)
print("Value of a after function call: ",a)

Output:
Value of a before function call: 10
Change made in function: 15
Value of a after function call: 10

2) Passing mutable arguments in function call:


When mutable type arguments (eg. List or Dictionaries) are passed in a function call then
any change in the value of mutable type will not change the memory address of the
variable. So after returning from function definition, it shows the changed value.

Example 1:
def myFunc1(myList):
print(" \t Inside myFunc1( )")
print(“\t List received:” , myList)
myList[0] += 2
print(“ \t List within called function, after changes: “, myList)
return
List1 = [1]
print("List before function call: ", List)
myFunc1(List1) #passing argument is a list, a mutable type
print("List after function call: ”, List1)

Output:
List before function call: [1]
Inside myFunc1( )
List received: [1]
List within called function, after changes: [3]
List after function call: [3]
Example 2: Passing Mutable Type Value to a function – Adding /Deleting items to it
def myFunc2(myList):
print(" \t Inside myFunc2( )")
print(“\t List received:” , myList)
myList.append(2)
myList.extend( [5,1] )
print(“ \t List after adding some elements : “, myList)
myList.remove(5)
print(“\t List within called function, after all changes:”, myList)
return
List1 = [1]
print("List before function call: ", List1)
myFunc2 (List1) #passing argument is a list, a mutable type
print("List after function call : ”, List1)

Output:
List before function call: [1]
Inside myFunc2( )
List received: [1]
List after adding some elements: [1,2,5,1]
List within called function, after all changes:”.[1,2,1]
Example 3: Passing Mutable Type Value to a function – Assigning parameter to a new
value or variable

def myFunc3(myList):
print(" \t Inside myFunc3( )")
print(“\t List received:” , myList)
new = [3,5]
myList = new
myList . append(6)
print(“\t List within called function, after all changes:”, myList)
return
List1 = [1, 4]
print("List before function call: ", List1)
myFunc3 (List1) #passing argument is a list, a mutable type
print("List after function call: ”, List1)

Output:
List before function call: [1,4]
Inside myFunc3( )
List received: [1,4]
List within called function, after all changes: [3,5,6]
List after function call : [1,4]

********************

You might also like