Skip to main content
SEE CS 2083 LEARN • PRACTICE • SUCCEED 🔍
Showing posts sorted by relevance for query Programming in Python PDF. Sort by date Show all posts
Showing posts sorted by relevance for query Programming in Python PDF. Sort by date Show all posts

Thursday, May 28, 2026

📘 4.2 User-defined Functions [Python Programming] - SEE COMPUTER SCIENCE 2083 - CDC NEW CURRICULUM

 📘 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

Monday, June 8, 2026

4.2 USER-DEFINED FUNCTIONS IN PYTHON

                                          DOWNLOAD PDF

4.2 USER-DEFINED FUNCTIONS IN PYTHON

What is a Function?

A function is a block of organized and reusable code designed to perform a specific task.

Functions help reduce repetition and make programs easier to manage.

 

Advantages of Functions

v  Reuse code multiple times.

v  Reduce code duplication.

v  Improve program readability.

v  Make debugging easier.

v  Support modular programming.

 

Modularity

Modularity means dividing a large program into smaller and manageable parts called functions or modules.

 

Types of Functions in Python

There are two types of functions:

v  Built-in Functions

v  User-defined Functions

 

1. Built-in Functions (Library Functions)

Functions already provided by Python are called built-in functions.

These functions are automatically available.

 

Common Built-in Functions

Function

Purpose

Examples

print( )

Displays output

print("Hello")

input( )

Takes input

 

len( )

Returns length

len("Python")

int( )

Converts into integer

int("5")

sum( )

Calculates total

sum([1,2,3])

 

2. User-defined Functions

A function created by the programmer using the def keyword is called a user-defined function.

Example

def greet( ):
    print("Hello")

 

Difference Between Built-in and User-defined Functions

Feature

Built-in Function

User-defined Function

Creator

Python Developers

Programmer

Availability

Available by default

Must be created

Loading

Loaded automatically

Loaded when defined

Example

print( )

add( )

Creating a User-defined Function

Syntax

def function_name(parameters):
    statements
    return value

 

Example Program

def add_numbers(x, y):
    total = x + y
    return total

print(add_numbers(5, 6))

Output

11

 

Important Rules of Functions

v  Function definition starts with def

v  Function header ends with colon :

v  Indentation is compulsory

v  Function name should be meaningful

v  Parameters are optional

v  Return statement is optional

 

Return Statement

A statement used to send a value back from a function.

Syntax

return value

 

Function Returning Value

Example

def area(length, width):
    return length * width

result = area(5, 8)

print(result)

Output

40

 

Parameters and Arguments

 

Parameter

A variable written inside the function definition is called a parameter.

Example

def area(radius):

radius is a parameter.

 

 

 

Argument

The actual value passed during the function call is called an argument.

Example

area(5)

5 is an argument.

 

Difference Between Parameter and Argument

Parameter

Argument

Placeholder

Actual value

Used in definition

Used in function call

Variable

Value

 

Example

def add(x, y):
    return x + y

add(5, 3)

Item

Type

x, y

Parameters

5, 3

Arguments

 

Scope of Variables

Scope determines where a variable can be accessed.

Types of Scope

v  Local Scope

v  Global Scope

 

Local Scope

Variables declared inside a function and accessible only within that function.

Example

def test():
    num = 5
    print(num)

test( )

 

Global Scope

Variables declared outside functions and accessible throughout the program.

Example

num = 10

def show( ):
    print(num)

show( )

 

 

 

Passing Arguments

Python supports three types of arguments.

v  Positional Arguments

v  Default Arguments

v  Keyword Arguments

 

1. Positional Arguments

Arguments are passed in the same order as parameters.

Example

def check(a, b, c):
    print(a, b, c)

check(2, 5, 7)

Output

2 5 7

 

2. Default Arguments

Parameters are assigned default values.

Example

def power(base, exp=2):
    return base ** exp

print(power(4))
print(power(2,3))

Output

16
8

 

Important Rule for Default Arguments

✅ Required parameters first
✅ Default parameters last

 

Legal Function

def interest(prin, time, rate=0.10):

Illegal Function

def interest(prin, time=2, rate):

❌ Error occurs because default arguments must come after required arguments.

 

3. Keyword Arguments

Arguments are passed using parameter names.

Order does not matter.

Example

def interest(prin, time, rate):
    pass

interest(rate=0.10, prin=2000, time=2)

 

 

Types of Functions Based on Return Value

v  Void Function

v  Non-Void Function

 

Void Function

A function that does not return any value.

Example

def greet( ):
    print("Hello")

Python automatically returns None.

Example

def greet():
    print("Hello")

a = greet( )

print(a)

Output

Hello
None

 

Non-Void Function

A function that returns a value.

Example

def add(x, y):
    return x + y

result = add(5,3)

 

Returning Multiple Values

Python can return multiple values using one return statement.

Example

def squared(x, y, z):
    return x*x, y*y, z*z

print(squared(2,5,7))

Output

(4, 25, 49)

 

Example with Variables

def squared(x, y, z):
    return x*x, y*y, z*z

a, b, c = squared(2,3,4)

print(a, b, c)

Output

4 9 16

 

Common Exam Mistakes ❌

v  Forgetting colon : after function definition

v  Wrong indentation

v  Confusing parameter and argument

v  Writing default arguments before required arguments

v  Forgetting to call the function

 

Most Important Programs for SEE Exam

Program 1: Add Two Numbers

def add(a, b):
    return a + b

print(add(5, 3))

 

Program 2: Find Area of Rectangle

def area(length, width):
    return length * width

print(area(5, 8))

 

Program 3: Default Argument

def power(base, exp=2):
    return base ** exp

print(power(4))

 

Program 4: Keyword Argument

def student(name, age):
    print(name, age)

student(age=15, name="Ram")

 

Program 5: Local and Global Variable

x = 10

def show( ):
    y = 5
    print(x)
    print(y)

show( )

 

Home 📖Chapters 🎯Quiz MCQs 🔍Search