📘 4.2 User-defined Functions [Python Programming] - SEE COMPUTER SCIENCE 2083 - CDC NEW CURRICULUM
DOWNLOAD PDF NOTES [4.2 USER DEFINED FUNCTIONS]
📘 4.2 User-defined
Functions [Python Programming]
A Python function is a block of organized and reusable
code designed to perform a specific task.
Functions provide better modularity for applications
and reduce code repetition through reusability.
Modularity: Breaking down a large, complex
application into smaller, manageable blocks.
Types of Python Functions
1. Built-in Functions (Library Functions)
Functions that are already available in Python are
called built-in functions. They are loaded into the computer's memory as soon
as the Python interpreter starts.
Example:
- print ( ) -
Displays output
- input ( ) -
Takes input from the user
- len ( ) -
Returns the length of a string or list
- int ( ) -
Converts a value to an integer
- sum ( ) -
Calculates the sum of elements
2. User-defined Functions
Functions created by the programmer to perform a
specific task are called user-defined functions. User-defined functions are
written using the def keyword. Once defined, they can be called multiple times
in a program.
Difference Between Built-in Functions and User-defined
Functions
|
Feature |
Built-in Functions |
User-defined Functions |
|
Creator |
Created by Python developers. |
Created by the user / programmer. |
|
Availability |
Available by default in Python without importing
additional modules. |
Must be written before using. |
|
Memory |
Loaded immediately when interpreter starts. |
Loaded only when defined in your code. |
|
Examples |
print(), len() |
calculate_tax ( ) |
|
Real-Life Example |
Readymade clothes from a store. |
Tailor-stitched custom clothes. |
Creating User-defined Functions
A function definition begins with the keyword def
(short for define). The syntax for creating a user-defined function is as
follows:
Syntax
def <function_name> (parameter1, parameter2,
...):
set of
instructions to be executed
[return
<value>]
Important Points
i. The items enclosed in “[ ]” are optional
parameters. Therefore, a function may or may not have parameters. Similarly, a
function may or may not return a value.
ii. The function header always ends with a colon (:).
iii. The function name should be unique. The rules for
naming identifiers also apply to function names.
iv. The statements outside the function indentation
are not considered part of the function.
Example
# Program to illustrate the use of user-defined
functions
def add_numbers(x, y):
total = x +
y
return total
num1 = 5
num2 = 6
print("The sum is", add_numbers(num1, num2))
Output
The sum is 11
Scope of Function
The scope of a function refers to the area of a
program where a function or variable can be accessed.
Generally, scope can be classified into the following
types:
i. Local Scope
Variables declared inside a function are accessible
only within that function.
ii. Global Scope
Variables declared outside any function can be
accessed from anywhere in the program.
Functions Returning a Value
The return statement in Python is used to return a
value back to the calling function. A function can take input values as
parameters, process them, and return the output using the return statement.
Usually, function definitions have the following basic
structure:
Syntax
def function_name(arguments):
return
<value>
Example
# Function to calculate the area of a rectangle
def area(length, width):
return
length * width
length = 5
width = 8
result = area(length, width)
print("Area of Rectangle:")
print(result)
Output
Area of Rectangle:
40
Parameters and Arguments in Functions
Parameters are the variables written inside the
parentheses in a function definition. These values are required for the
function to work.
Example
# Function to
calculate the area of circle using function
def area_of_circle(radius):
area =
radius ** 2 * 22 / 7
return area
radius =
float(input("Please enter the radius of the given circle: "))
print("The area of the given circle is:", area_of_circle(radius))
An argument is an actual value passed to a function.
In other words, arguments are the values provided in the function call
statement.
The list of arguments should match the order of
parameters in the function definition.
Example of argument in function call
area(5)
5 is an argument. An argument can be constant,
variable, or expression.
Parameters are
actually variables/placeholders, not values.
Arguments are the actual values passed during function call.
Scope of Variables
The scope of a variable determines where the variable
can be accessed in a program.
The two common types of variable scope are:
1. Local Scope
2. Global Scope
1. Local Scope
Variables declared inside a function are called local
variables. These variables can only be accessed within that function. A local
variable exists only while the function is executing.
Example
def
multiply_by_two():
number = 5 # local variable
result = number * 2
print("Inside function:",
result)
multiply_by_two()
# print(result) # This will give an
error because 'result' is local to the function
Output
Inside function: 10
2. Global Scope
Variables declared outside all functions are called
global variables. These variables can be accessed from anywhere in the program.
Example
number = 10 # global variable
def add_five():
result = number + 5
print("Inside function:",
result)
add_five()
print("Outside function:", number)
Output
Inside function:
15
Outside function: 10
Passing Parameters
Python allows different ways to pass data (arguments)
into a function.
Python supports three types of arguments:
1. Positional (Required) Arguments
2. Default Arguments
3. Keyword (Named)
1. Positional/Required Arguments
Arguments passed in the same order as the parameters
are defined are called positional or required arguments.
Example
If a function definition header is like
def check(a, b, c):
then function calls for this can be:
check(x, y,
z) # 3 values (all variables) passed
check(2, x, y) # 3 values (literal
variables) passed
check(2, 5, 7) # 3 values (all
literals) passed
2. Default Arguments
Default arguments are the parameters that take default
values if no value is provided during the function call.
Example
def interest(principal, time, rate=0.10):
here 0.10 is the default value for parameter rate
The default value is specified in a manner
syntactically similar to a variable initialization.
Example
def Interest(prin,
time, rate=0.10): # legal
def Interest(prin, time=2, rate):
# illegal
def Interest(prin=2000, time=2, rate):
# illegal
def Interest(prin, time=2, rate=0.10):
# legal
def Interest(prin=200, time=2, rate=0.10): # legal
Important point
Default parameters must always come after required
parameters.
Example 2
def power (base, exp = 2) :
return base
** exp
print (power(4))
print (power (2, 3))
Here, in the first function call, only one argument,
i.e. the base. So, it uses default value of exp, i.e. 2. In the second function
call, both arguments are defined so base = 2 and exp = 3.
Output
16
8
3. Keyword (Named) Arguments
Arguments passed using parameter names in a function
call, so the order does not matter, are called keyword (or named) arguments.
Examples
interest(prin=2000,
time=2, rate=0.10)
interest(time=2, prin=2600, rate=0.09)
interest(time=2, rate=0.12, prin=2000)
All the above function calls are valid now, even if
the order of arguments does not match the order of parameters as defined in the
function header.
Returning Values
from Functions
A function in Python can be defined with or without returning a value to the
calling function. There are two types of functions in Python:
1. Functions Returning Values (Non-void Functions)
2. Functions Not Returning Values (Void Functions)
1. Functions Returning Values (Non-void
Functions)
Functions that return a computed value to the calling
function are called non-void functions.
The return statement is used to return the value.
The returned value may be a literal (5), a variable
(x), or an expression (x + y).
Syntax
return <value>
Example
def add(x, y):
return x + y
result = add(5, 3)
Here, the returned value from add( ) replaces the
function call.
2. Functions Not Returning Values (Void
Functions)
Functions that perform a task but do not return any
value to the calling function are called void functions.
A void function may contain:
return
That is, the return statement without any value or
expression.
Examples of Void Functions
def greet():
print("Hello")
def greet1(name):
print("Hello", name)
def quote():
print("Python is good")
return
def printsum(a, b, c):
print("Sum is", a + b + c)
return
Important Point
Void functions do not return any value. However,
Python automatically returns a special value called None.
Example
def greet():
print("Hello")
a = greet()
print(a)
Output
Hello
None
Returning Multiple Values
Python allows a function to return multiple values
using a single return statement.
Syntax
return <value1>, <value2>, <value3>
Example
def squared(x, y,
z):
return x * x, y * y, z * z
t = squared(2, 5, 7)
print(t)
Output
(4, 25, 49)
Example
def squared(x, y,
z):
return x * x, y * y, z * z
v1, v2, v3 = squared(2, 3, 4)
print("The returned values are as under:")
print(v1, v2, v3)
Output
The returned
values are as under:
4 9 16










































