0% found this document useful (0 votes)
33 views

computer ch 2 notes Functions 2024-'25

Uploaded by

fatuba329
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)
33 views

computer ch 2 notes Functions 2024-'25

Uploaded by

fatuba329
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/ 14

Computer Science Notes

Functions
Modular Programming:

The process of dividing a computer program into separate independent blocks of code or separate sub-
problems with different names and specific functionalities is known as modular programming.

In programming, the use of function is one of the means to achieve modularity and reusability.

Functions:

Function can be defined as a named group of instructions that accomplish a specific task when it is
invoked.

Once defined, a function can be called repeatedly from different places of the program.

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.

Different types of functions


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

ii)Functions defined in modules: These functions are predefined in a particular module and can only be
used when the corresponding module is imported.
E.g.
import math
a = 144
print(math.sqrt(a))

iii)User defined functions: These are the functions defined by the programmer as per the requirement.
General format of user defined functions in python
def <function name> ([Parameter1, Parameter2,……]) :
<stm1>
<stm2>
. function body
.
[return statement]
Function header: The first line of a function definition that begins with keyword def and ends with a
colon (:)
Function name should be unique. Rules for naming identifiers also applies for function naming.
The items enclosed in "[ ]" are called parameters and they are optional.
Parameters: Variables that are listed within the parameter list of a function header.
Function body: The block of indented statements beneath function header that defines the action
performed by the function. The function body may or may not return any value. A function may or may
not return a value

return statement: A function may or may not return a value when called. The return statement returns
the values from the function. Some function performs calculations and display result(s). They do not
return any value. Such functions are called void functions. But a situation may arise, wherein we need to
send value(s) from the function to its calling function. This is done using return statement.

The return statement does the following:

• returns the control to the calling function.

• return value(s) or None.

Fruitful functions and void functions: (Types of functions based on return values)

Functions returning some value (non-void functions / fruitful functions)

Functions not returning any value (void functions / non fruitful functions)

A function may or may not have parameters. Also, a function may or may not return a value.
Different types of user defined functions:
Type 1: User defined function without arguments and without return value (void functions without any
arguments)
E.g.
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 and Called function (Callee)


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.

Arguments: An argument is a value passed to the function during the function call which is received in
corresponding parameter defined in function header.

Difference between arguments and parameters:


The values being passed through a function call statement are called arguments.
The values received in the function definition/function header are called parameters.
E.g.:
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. X, Y are arguments.
Arguments Parameters
Values being passed are called arguments Values being recieved are called arguments
Arguments appear in function call Parameters appear in the function header
Arguments are also known as actual parameters Paramaters are also known as formal parameters
or actual arguments or formal arguments

Default Parameter
A default value is a value that is pre-decided and assigned to the parameter when the function call does
not have its corresponding argument.
* A default parameter 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
A required parameter should not come after a default parameter in a function definition.
In other words, the default parameters must be the trailing parameters in the function header. Or, if any
parameter is having a 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 default parameters
• It can be useful in situations where some parameters generally 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.

Positional arguments:
Positional arguments are arguments passed to a function in correct positional order. The number and
order of arguments passed should match with the parameter list in the function header.
E.g. 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

Keyword (Named Arguments):


Arguments for which names are specified for the values being passed in the function call are called
keyword arguments.
* If the functions have many arguments and we want to change their sequence, then we have to use
keyword arguments
*The biggest benefit of keyword argument is that we need not remember the position of the argument
*For this whenever we call the function, pass the arguments with argument names.

E.g.
def interest (P, R,T ) :
SI = (P*R*T) /100
print(“Simple Interest =”, SI)
interest(P=2000,T=2,R=10)
interest(T=4,P=2600,R=9)
interest(T=2,R=12,P=2000)
Flow of Execution:
Flow of execution can be defined as the order in which the statements in a program are executed.
The Python interpreter starts executing the instructions in a program from the first statement. The
statements are executed one by one, in the order of appearance from top to bottom.
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.
Values returned by a function
The value being returned by a function can be one of the following: i) a literal ii) a variable iii) an
expression
E.g.
return 5 # literal being returned
return 6+4 # expression involving literals being returned
return a # variables 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.
E.g.
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)
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)
Functions Returning multiple values:
In Python, a function may return multiple values. In multiple returning, it returns a sequence of values to
the calling statement.
The function call statement should receive or use the returned values in one of the following ways:
Either receive the returned value in form of a tuple variable
Or
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.
a) Receiving the returned value in form of a tuple variable
E.g.
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 unpacking the received values of tuple by specifying the same number of variables on the
left hand side of the assignment in function call.
E.g.
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)
Scope of a Variable:
The part of the program where a variable is accessible can be defined as the scope of that variable.
Global Variable:
In Python, a variable that is defined outside any function or any block is known as a global variable. It
can be accessed in any functions defined onwards.
Any change made to the global variable will impact all the functions in the program where that variable
can be accessed.
Local Variable:
A variable that is defined inside any function or a block is known as a local variable. It can be accessed
only in the function or a block where it is defined.
It exists only till the function executes.

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
It is a variable declared within a function or It is a variable declared outside all the functions
within a block.
It is accessible only within a function / block in It is accessible throughout the program
which it is declared.
Lifetime of a local variable is their function’s run. Life time of a global variable is entire program
run.
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


Scope resolution rules:
Case 1: Variable in local scope
E.g.
def greet( ):
name=”Cathy”
print(“Hello”, name) # name is a local variable . ( First it checks in local environment and
#finds it there and prints it.)
greet( )

Case 2 : Variable in global scope


E.g.
def calcsum( x, y) :
s= x + y
print(num1) #variable num1 is a global variable not a local variable.( First it checks
return s #num1 in local environment ,not found, then it checks the global
#environment, it finds num1 there, so it picks its value and prints it.)
num1 = int(input(“Enter first number : “))
num2 = int(input(“Enter second number:”))
print(“Sum is”, calcsum(num1,num2))
o/p
Enter first number: 3
Enter second number: 7
Sum is 10

Case 3 : Variable neither in local scope nor in global scope


Eg)
def greet( ):
print(“Hello”, name) #This would return error as name is neither in local environment
# nor in global environment
greet( )
Case 4: Same variable name in local scope as well as in global scope
When a local variable is created with same name as that of global variable, it hides the global variable
in function definition.
Eg)
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:
Global variables can be accessed inside a function, but their values cannot be modified unless it is a
mutable type.

Modifying global values in a function:


To modify global values in a local scope we use the global statement
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:
Once a variable is declared global in a function, you cannot undo the statement. (i.e., after a
global statement, the function will always refer to the global variable and local variable cannot
be created of the same name.)

Passing immutable arguments and mutable arguments in function call.


When immutable type arguments (e.g., 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
When mutable type arguments (e.g., 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.
E.g.
def change(x):
x.append(5)
print("Change made in function: ",x)
a=[10,12]
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, 12]
Change made in function: [10, 12, 5]
Value of a after function call: [10, 12, 5]

Note: If a new variable is created with the same name in the function, then it will hide the argument
passed to the function. Then the change made will not reflect in the original value passed.
E.g.
def change(x):
x=[100,120]
x.append(5)
print("Change made in function: ",x)
a=[10,12]
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, 12]
Change made in function: [100, 120, 5]
Value of a after function call: [10, 12]
How do mutable type arguments behave with functions?
Ans) Changes are reflected in caller function if its name is not assigned a different value.
Changes are not reflected in the caller function if it is assigned a different value.

You might also like