0% found this document useful (0 votes)
25 views15 pages

CHAPTER-3 Working with functions notes

The document provides an overview of functions in Python, including their types (built-in, module-defined, and user-defined) and how to define and invoke them. It explains key concepts such as function headers, parameters, arguments, and the flow of execution during function calls. Additionally, it covers the distinction between functions that return values and those that do not, as well as the scope of variables within programs.

Uploaded by

rajputalpumanish
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)
25 views15 pages

CHAPTER-3 Working with functions notes

The document provides an overview of functions in Python, including their types (built-in, module-defined, and user-defined) and how to define and invoke them. It explains key concepts such as function headers, parameters, arguments, and the flow of execution during function calls. Additionally, it covers the distinction between functions that return values and those that do not, as well as the scope of variables within programs.

Uploaded by

rajputalpumanish
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/ 15

Saraswati International School

XII – Science
Computer Science (083)
CHAPTER: 3 Working with Function

Function: Functions are the subprograms that perform specific task. Functions are the
small modules.

Types of Functions:

There are three types of functions in python:

Built-in Functions

Functions defined in modules

User defined functions

1. Built-in functions: These are pre-defined functions and are always available for use.
Eg: type( ) , int( ), float( ), len( ),print( ) etc.

2. Functions defined in modules: These functions defined in particular modules. When


you want to use these functions in program, you have to import the corresponding
module of that function. Eg: pow( ) function of math module.

3. User Defined Functions: The functions those are defined by the user are called user
defined functions.
Defining function in Python:
➢ Statement to perform operation written as a separate block with function name /
header is called function definition.
➢ A function once defined can be invoked as many times as needed by using its name,
without having to rewrite its code.
➢ The syntax to define a function is: def function-name ( parameters) :

statement(s)
:
➢ Where:
• Keyword def marks the start of function header.
• A function name to uniquely identify it. Function naming follows the same rules of
writing identifiers in Python.
• Parameters (arguments) through which we pass values to a function. They are optional.
• A colon (:) to mark the end of function header.
• One or more valid python statements that make up the function body. Statements must
have same indentation level.
• An optional return statement to return a value from the function.
• Example:
(i) Function with parameter:
def display(name):
print("Hello " + name + " How are you?")
(ii) Function without parameter:
def greet( ):
print( “Good Morning”)
❖ Some important terms:
1. Function Header: The first line of function definition that begins with keyword def and
ends with a colon (:), it specifies the name of the function & its parameters.
2. Parameters: variables that are listed within the parentheses of function header.
3. Function Body: The block of statement inside function header that defines the action
performed by the function. The function body may or may not return any value.
4. Indentation: The blank space in the beginning of a statement within a block.

• Note: The function definition does not execute the function body; this gets executed
only when the function is called or invoked.
Calling / invoking / using a function:
➢ To use a function that has been defined earlier, you need to write a function call
statement.
➢ Syntax: <function_name>(<value to be passed to argument>)
➢ Eg: if want to call function display defined above, function call statement will be:
display(“Rohan”)
➢ Carefully notice that number of values being passed is same as number of parameters.
➢ Variables/values passed using parentheses ( ) , in function definition is a function
parameters and in function call is argument.

➢ Consider one more example:


def cube(X):
res = X ** 3
return res # return computed value.

➔ Now, its function call statement would be similar to ones shown below:
1. Passing literal as argument:
cube (4) #pass value 4 to variable X

2. Passing variable as argument:


num = 4
cube (num) #pass value of variable num i.e., 4 to parameter X

3. Passing user’s input as argument:


num = int (input (“Enter a number:”))
cube (num) #pass value of variable num i.e., 4 to parameter X

4. Using function call inside another statement (print statement):


print(cube(4)) # cube(4) will first get computed result, which will be then printed

5. Function call inside expression:


doubleOfCube = 2 * cube(4)
#function call result will be multiplied with 2 and stored in variable doubleOfCube
Structure of a Python Program
➢ In Python program, generally all function definitions are given at the top followed by
statements which are not part of any function.
➢ These statements are not indented at all.
➢ These are often called from the top-level statements.
➢ Interpreter starts the execution of a program from top-level statements.
➢ Internally Python gives a special name to top-level statements as __main__
➢ Syntax: def function1( ):
Statement 1
Statement 2
#top-level statements →top-level statements, Python begins execution
Statement 1 from here.
Statement 2 → Python names this segment as __main__
:
➢ Python stores this name in a built-in variable called __name__
➢ Eg: def greet( ):
print(“good morning”)
print(“Inside: “,__name__)

Flow of execution in a function call:


➢ “The flow of execution refers to the order in which statements are executed during a
program run.”
➢ A function body is also a block. In Python, a block is executed in an execution frame .
➢ An execution frame contains:

Some internal information (used for debugging)

Name of the function

Value passed to function

Variables created within function

Information about the next instruction to be executed


➢ Whenever a function call statement is encountered, an execution frame for the called
function is created & control is transferred to it.
➢ Program execution begins with the first statement of __main__ segment.
➢ Eg:
1. def sum(X ,Y):
2. S=X+Y
3. return S
#top-level statement(__main__ segment)
4. Num1 = int(input(“Enter first number:”))
5. Num2 = int(input(“Enter second number:”))
6. Calc_sum = sum(Num1, Num2) #function call Num1 and Num2 will be copied
to X and Y respectively an computed result
stored to variable Calc_sum
7. print(“Sum of two numbers:” , Calc_sum)

✓ In the above example the statements were executed as (control/execution flow):


1 → 4 → 5 → 6 → 1 → 2 → 3 → 6 → 7 (Statement number)

Function Parameters and Arguments:


1. Parameters (Formal Parameter): value being received in the function definitions
referred to as parameter also called formal parameters.
• Formal parameters are written in the function prototype (definition) and function
header of the definition. Formal parameters are local variables which are assigned
values from the arguments when the function is called.

2. Argument (Actual Parameter): When a function is called, the values that are passed
in the call are called argument also called actual parameters. At the time of the call
each actual parameter is assigned to the corresponding formal parameter in the
function definition.

Passing Parameters:
➢ The number of argument should be same as number of parameters required.
➢ Python supports three types of formal argument/parameter:
1. Positional arguments (Required arguments)
2. Default arguments
3. Keyword arguments (Named arguments)
1. Positional/Required arguments:
➢ When the function call statement must match the number of argument and order
of arguments as defined in the function definition, this is called the positional
argument matching.
➢ Eg: def check(a,b,c)
Function call: check (x,y,z) OR check(2,x,y)

2. Default arguments:
➢ Python allows us to assign default values to a function’s parameters which are
useful in case a matching argument is not passed in the function call statement.
➢ It is useful when actual parameters are/is skipped during function call.
➢ The default values are specified in the function header of function definition.
➢ The default values are considered only if no value is provided for that parameter in
the function call statement.
➢ “A parameter having default value in the function header is known as a default
parameters”
➢ Eg: def interest(principal,time,rate=0.10)
➢ Function call: si_int = interest(5000,2,0.5)
✓ Here no value is skipped in function call. hence it will not use default value and
the value for variable is principal =5000, time=2, rate=0.5
➢ But if the function call, si_int = interest(5000,2)
✓ Here, the value for rate i.e., last value is missing. Hence it will use default value
0.10 of rate. Now the values are principal = 5000, time = 2 , rate = 0.10
• Important: In a function header, any parameter cannot have a default value unless all
parameters appearing on its right have their default values.
• EG:
i. def interest(principal, time =2 , rate) #Invalid
ii. def interest(principal=5000, time = 2, rate = 0.10) #valid
iii. def interest (principal=5000, time, rate) #Invalid
iv. def interest(principal=5000, time = 2, rate) #Invalid
v. def interest(principal, time , rate = 0.10) #valid
vi. def interest(principal, time = 2, rate = 0.10) #valid
❖ Advantage of default parameter:
➢ Default parameters can be used to add new parameters to the existing function.
➢ It can be used to combine similar functions into one.
3. Keyword / Named Argument:
➢ Default arguments give you flexibility to specify the default value for parameter so
that it can be skipped in the function call if needed.
➢ However, still you cannot change the order of the arguments in the function call. You
have to remember the order of the arguments.
➢ To have complete control over the values, Python offers another type of arguments:
keyword argument
➢ “Keyword arguments are the named arguments with assigned value being passed in
the function call statement.”
➢ Eg: si_int =interest( rate = 0.10, principal = 5000, time = 2)
o Here, you can change the order of parameters because you used keyword
argument i.e. value passed with its name.

Using Multiple argument types together:


➢ Python also allow you to combine multiple argument types in a function call.\
➢ Eg: if a function definition header is:
def interest(principal = 3000, rate = 0.10, time = 2)
• Interest(5000, time = 5) #Function call
✓ Here, 5000 will be copied to principal and it is positional argument.
✓ 5 will be copied to time and it is keyword argument.
✓ There is no value passed for third parameters rate hence it will use
default parameter (0.10) of parameter rate.
Important:
• Having positional arguments after keyword argument will result into error.
• If argument does not have default value in function definition then the function call
statement cannot skip that argument.

Returning values from functions:


➢ Functions in Python may or may not return values.
➢ There can be broadly two types of functions:
1. Functions returning some value [Non void / fruitful function]
2. Function not returning any value [void / non-fruitful function]
1. Functions returning some value [Non void / fruitful function] :
➢ The functions that return some computed result in terms of a value is called Non void
or fruitful function.
➢ The computed value is returned using return statement like, return <value>
➢ The value being returned can be:
• A literal
• A Variable
• An expression
➢ Eg:
• return 5 #literal being returned
• return 6 + 4 #expression involving literal
• return a** 3 #expression involving literal variable
• return a # variable being returned
• Important:
➢ The returned value of a function should be used in the caller function/program inside
an expression / a statement.
➢ The returned value should be used in:
i. With an assignment statement as, Calc_sum = sum(Num1, Num2)
ii. With print Statement as, print(sum(Num1, Num2))
iii. With a relational expression as, Sum(Num1 > Num2) > 6
✓ If you do not use their value in any of these ways and just give a standalone
function call, Python will not report an error but their return value is
completely wasted.
➢ The return statement ends a function execution even if it is in the middle of the
function:
➢ Eg: def check(a) :
a = math.fabs(a)
return a
print(a) # This statement is unreachable because check( )
check ( -15) function will end with return statement

2. Functions not returning any value [void / Non-fruitful function] :


➢ The functions that perform some action or do some work but do not return any
computed value or final value to the caller are called void or non-fruitful function.
➢ A void function may or may not have a return statement.
➢ If void function has a return statement, then it takes the form as,
return #keyword return without any value or expression
➢ Eg: i) void function without return statement:
def greet( ):
print(“ Good morning”)

ii) void function with return statement:


def sum(a,b):
print(“Sum is:”,a+b)
return
➢ The void functions are generally not used inside a statement or expression in the
caller ; their function call statement is standalone complete statement in itself.
➢ Eg for the above functions, the function call statements will be,
i) greet( )
ii) sum(4,6)
➢ The void functions do not return a value but they return a legal empty value of
Python i.e., None
➢ Eg: def greet( ):
print(“Good morning”)
a = greet( )
print(a)
Output: Good morning
None
❖ Returning Multiple values:
➢ To return multiple values from a function, you have to ensure following things:
i. The return statement inside a function body should be of the given form given
below:
return <value1/variable1/exp 1> , <value2 / variable 2 / exp 2>
ii. The function call statement receive or use the returned values in one of the
following ways:\
a) Either receive the returned values in form of a tuple variable as,
def squared(x , y, z):
return x * x, y * y, z * z
t = squared(2 , 3 , 4) # stores result as tuple
print(t)
Output: (4 , 9 , 16)
b) Or you can 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 as,
def squared(x , y, z):
return x * x, y * y, z * z
v1 , v2 , v3 = squared(2 , 3 , 4) # stores result as tuple
print(v1 , v2, v3)
Output: 4 9 16

Composition:
➢ “Composition in general refers to using an expression as a part of a large expression
or statement as a part of large statement.”
➢ An arithmetic expression: greater((4+5),(3+4))
➢ A logical expression: test (a or b)
➢ Function call as part of large function call i.e., composition : int(str(53))

Scope of variable:
➢ “part of program within which a name is legal and accessible, is called scope of
variable.”
➢ There are broadly two kinds of scopes:
i) Global scope ii) Local scope

i) Global scope: A name / variable 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) contained within the program.
Eg: x=5 # global variable, can be use anywhere in prog.
def fun(a):
b= a+1
print(x) # x can be used in function also because it is global
return b
y = int(input(“Enter number:”))
z = y + fun(x) # x , y, z are global variables
print(z)
ii) Local Scope: A name declared in a function body is said to have local scope i.e., it can
be used only within the function.
Eg: def sum( x , y): #x and y are local variables can be used only within the function sum
z=x+y
return z
n1 = int(input( “Enter first number:”))
n2 = int(input( “Enter second number:”))
s = sum(n1 , n2)
print(s)
❖ Lifetime: The time for which a variable or name remains in memory is called lifetime of
variable.
➔ For global variable: life time is entire program run
➔ For local variable: life time is their function’s run
Name Resolution (Resolving Scope of a Name):
➢ When you access a variable in program or function, Python follows name resolution
rule, also known as LEGB rule.
➢ For every name, Python does the following to resolve it:
i. It checks within its Local environment (LEGB), if variable with same name available or
not, if yes Python use it, if no it moves to step (ii).
ii. Python now checks the Enclosing environment (LEGB), if variable with same name
available or not, if yes Python use it, if no it moves to step (iii).
iii. Python now checks the Global environment (LEGB), if variable with same name
available or not, if yes Python use it, if no it moves to step (iv).
iv. Python now checks the Built-in environment (LEGB), if variable with same name
available or not, if yes Python use it otherwise Python would report an error.

Built-in namespace 4
Global namespace 3

Enclosing namespace 2

Local namespace 1
❖ Some Examples:
• Case: 1 Variable in global scope:
def sum( x , y):
z=x+y
print(n1,n2) #it will first check local scope and enclosing scope but variable
n1 and n2 are not in local or enclosing environment so now it will
check global environment and prints its value.
return z
n1 = int(input( “Enter first number:”))
n2 = int(input( “Enter second number:”))
s = sum(n1 , n2)
print(s)
• Case: 2 Variable neither in local scope nor in global scope:
def greet( ) :
print(“hello”, name)
print(“Hi”)
greet( )
➔ If variable used in code is neither assigned in local nor in global then will Python return
ERROR.

• Case: 3 Some variable name in local scope as well as in global scope:


➔ A local variable created with the same name as that of global variable, it hides the global
variable.
def state1( ):
tiger = 15 #local variable, hides global variable
print(tiger)
tiger = 95 #global variable
print(tiger)
state1( )
print(tiger)
Output: 95
15
95
❖ What if you want to use the global variable inside local scope?
➢ To tell function that for particular variable name, do not create local variable but use
global variable instead (to unhide global variable) use global statement.
➢ “The global statement is a declaration which holds for the entire current code block.”
➢ Eg: def state1( ):
global tiger #unhide global variable(refers to global variable)
tiger = 15
print(tiger)
tiger = 95 #global variable
print(tiger)
state1( )
print(tiger)
Output: 95
15
15

• Important: Once a variable is declared global in function, you cannot undo the
statement. One should avoid using global statement in Python. After a global statement,
the function will always refer to global variable.

Mutable /Immutable properties of passed data objects:


➢ If variable is referring to an immutable type then any change in its value will also change
the memory address it is referring to. But, if a variable is referring to mutable type then
any change in the value of mutable type will not change the memory address of gthe
variable.
❖ Mutability/immutability of arguments/Parameters and Function calls:
➢ When you pass values through arguments and parameters to a function,
mutability/immutability also plays an important role.
i. Passing an Immutable Type Value to a function
def myfun(a):
print(“Value received is:”,a)
a+=2
print (“Value now changes to:”, a)
#__main__
Num = 3
print(“Value before calling function: “, Num)
myfun(Num)
print(“Value after returning from function:”,Num)
Output:
Value before calling function: 3
Value received is: 3
The value got changed
Value now changes to: 5
from 3 to 5 inside function
Value after returning from function: 3
BUT NOT got reflected to
__main__
ii. A) Passing a Mutable Type Value to a function – Making changes in place
def myfun(a):
print(“List received is:”,a)
a [0]+ = 2
print (“List now changes to:”, a)
#__main__
List = [1]
print(“List before function call: “, List)
myfun(List)
print(“List after function call: “, List)

Output:
List before function call: [1]
List received is: [1]
The value got changed
Value now changes to: [3]
from [1] to [3] inside
Value after returning from function: [3]
function and change GOT
REFLACTED to __main__
B) Passing a Mutable Type Value to a function – Adding/deleting items to it
def myfun(a):
print(“List received is:”,a)
a.append(2)
a.extend([5,1])
print (“List after adding some elements:”, a)
a.remove(5)
print (“List after all changes:”, a)
#__main__
List = [1]
print(“List before function call: “, List)
myfun(List)
print(“List after function call: “, List)
Output:
List before function call: [1]
List received is: [1]
Value now changes to: [1,2,5,1]

List after all changes: [1 , 2, 1] The value got changed


from [1] to [1, 2, 1] inside
List after function call: [1 , 2, 1] function and change GOT
REFLACTED to __main__

C) Passing a Mutable Type Value to a function – Assigning parameter to a new


value/variable:
def myfun(a):
print(“List received is:”,a)
new = [3 ,5]
a = new #parameter a assigned a new value
a.append(6)
print (“List after all changes:”, a)
#__main__
List = [1 , 4]
print(“List before function call: “, List)
myfun(List)
print(“List after function call: “, List)

Output:
List before function call: [1 , 4]
List received is: [1 , 4]

List after all changes: [3 , 5, 6] The value got changed from [1, 4]
to [3, 5, 6] inside function and
List after function call: [1 , 4] change DID NOT GET REFLACTED
to __main__

❖ That means, we can say that:


➢ Changes in immutable types are not reflected in the caller function at all.
➢ Changes, if any, in mutable types:
✓ Are reflected in caller function if its name is not assigned a different variable or
data type.
✓ Are not reflected in the caller function if it is assigned a different variable or data
type.

You might also like