0% found this document useful (0 votes)
20 views17 pages

Unit 3 Functions

Unit III covers functions in programming, detailing their importance in reducing redundancy and complexity, as well as enhancing modularity and readability. It explains parameters, arguments, return values, and introduces recursive and lambda functions, emphasizing their roles in code efficiency and structure. The document also provides examples and comparisons of different types of arguments and functions.
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)
20 views17 pages

Unit 3 Functions

Unit III covers functions in programming, detailing their importance in reducing redundancy and complexity, as well as enhancing modularity and readability. It explains parameters, arguments, return values, and introduces recursive and lambda functions, emphasizing their roles in code efficiency and structure. The document also provides examples and comparisons of different types of arguments and functions.
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/ 17

UNIT III

FUNCTIONS

Hiding redundancy, complexity; Parameters, arguments and return values; formal vs


actual arguments, named arguments, Recursive & Lambda Functions.

• A function is a block of reusable code that performs a specific task.

• Helps in modularity, readability, reusability, and reducing redundancy.


• Defined using the def keyword.

def greet():

print("Hello, welcome to Python!")

HIDING REDUNDANCY AND COMPLEXITY

• Without functions the code is repetitive.

• With functions the complex logic is hidden behind a function call.


• Benefits:

o Reduces redundancy (no need to write same logic multiple times).

o Hides complexity (users only call the function without worrying about
internal steps).

# Without function

print("Area:", 3.14 * 5 * 5)

print("Area:", 3.14 * 10 * 10)

# With function

def area_circle(r):

return 3.14 * r * r
print("Area:", area_circle(5))

print("Area:", area_circle(10))

• In programming, redundancy means repetition of code.

• Complexity refers to long, detailed, or difficult-to-understand code logic.

Functions help overcome these by:


o Hiding redundancy → Instead of writing the same code multiple times, we
define it once inside a function and reuse it.

o Hiding complexity → The internal logic of the function is hidden; the


programmer only calls the function with required inputs.

2. Why Important?

⚫ Makes programs shorter (avoids code duplication)

⚫ Improves readability and clarity

⚫ Promotes modularity (divide program into smaller parts)


⚫ Easier debugging, testing, and maintenance

⚫ Supports code reusability in multiple programs

3. Example – Without Function (Redundant Code)

# Calculate area of circle for 2 different radii

r1 = 5

area1 = 3.14 * r1 * r1
print("Area of circle 1:", area1)

r2 = 10

area2 = 3.14 * r2 * r2

print("Area of circle 2:", area2)

Problem → Formula is repeated → redundant and not reusable.

4. Example – With Function (Redundancy Hidden, Complexity Hidden)


def area_circle(r):

return 3.14 * r * r

print("Area of circle 1:", area_circle(5))

print("Area of circle 2:", area_circle(10))

Formula written only once (redundancy removed)


User doesn’t worry about formula → just calls area_circle(r) (complexity hidden)
5. Real-Life Analogy

• Think of a TV remote:

o You press a button (function call).


o Complex internal circuits and signals are hidden (complexity).

o You don’t need to repeat wiring every time (redundancy).

PARAMETERS, ARGUMENTS, AND RETURN VALUES

Parameters

• Variables defined inside the function definition that receive values.


• Example:
• def add(x, y): # x and y are parameters

• return x + y

Arguments

• Values passed when calling a function.

• Example:

• result = add(5, 7) # 5 and 7 are arguments

Return Values
• Functions can send results back using return.

• If no return, function returns None.

def square(n):

return n*n

print(square(4))

# Output: 16

Parameters
Definition

Parameters are variables listed inside the parentheses of a function definition.


They act as placeholders for values that will be passed into the function when it is called.
Parameters allow data to be transferred into functions for processing.

Example

def greet(name): # 'name' is a parameter

print("Hello,", name)
greet("John") # "John” is the argument

Purpose of Parameters

◆ Make functions generalized and reusable

◆ Provide inputs to functions dynamically

◆ Allow same function to work for different values

Types of Parameters in Python


Python supports multiple types of parameters:
(a) Positional Parameters

Values are assigned based on position.

def add(a, b):

return a + b

print(add(10, 20)) # a=10, b=20

(b) Default Parameters

Parameters can have default values if no argument is provided.


def greet(name="User"):

print("Hello,", name)

greet() # Hello, User

greet("Ravi") # Hello, Ravi

(c) Keyword Parameters

Arguments are passed using parameter names.

def student(name, age):


print(name, "is", age, "years old")

student(age=20, name="Meena")
(d) Variable-length Parameters
*args → allows multiple values (stored as a tuple).

**kwargs → allows multiple keyword arguments (stored as a dictionary).

def show_marks(*marks):

print(marks)
show_marks(78, 85, 92)

def student_info(**info):

print(info)

student_info(name="Arun", age=21, dept="CSE")

Parameters vs. Arguments

Parameters are variables in function definition.

Arguments are actual values passed when calling a function.


Example:
def add(x, y):

# x, y = parameters (formal)

return x + y

print(add(5, 7))

# 5, 7 = arguments (actual)

Arguments
• Arguments are the actual values supplied to a function when it is called.

• They are assigned to the parameters defined in the function.

Example

def add(a, b): # a, b = parameters

return a + b

print(add(5, 3)) # 5, 3 = arguments


Types of Arguments in Python

Python supports several ways of passing arguments:

(a) Positional Arguments

• Matched by position/order.
def divide(a, b):

return a / b

print(divide(10, 2)) # a=10, b=2

(b) Keyword Arguments

• Arguments matched by parameter name.

def student(name, age):

print(name, "is", age, "years old")


student(age=20, name="Meena")
(c) Default Arguments

• If no value is passed, the default value is used.

def greet(name="User"):

print("Hello,", name)

greet()

# Hello, User

greet("Ravi") # Hello, Ravi


(d) Variable-length Arguments

• *args → accepts multiple positional values (tuple).

• **kwargs → accepts multiple keyword values (dictionary).

def show_marks(*marks):

print(marks)

show_marks(78, 85, 92) # (78, 85, 92)

def student_info(**info):
print(info)

student_info(name="Arun", age=21, dept="CSE")


FORMAL VS ACTUAL ARGUMENTS

• Formal Arguments are variables in function definition.

• Actual Arguments are values/data passed during function call.

def add(a, b):


# a and b = formal arguments

return a+b

sum1 = add(10, 20) # 10 and 20 = actual arguments

Actual values are copied into formal parameters when function is invoked.

TYPES OF FUNCTION ARGUMENTS IN PYTHON

1. Positional Arguments – based on position.


2. Keyword Arguments – specify name explicitly.
3. add(b=5, a=3)

4. Default Arguments – function parameters with default values.

5. def greet(name="User"):

6. print("Hello", name)

7. greet() # Hello User

8. Variable-length Arguments:

o *args → tuple of variable arguments


o **kwargs → dictionary of keyword arguments

RECURSIVE FUNCTIONS

• A function that calls itself until a base condition is met.

• Useful for problems that can be broken into smaller sub problems (factorial,
Fibonacci, tree traversal).

def factorial(n):

if n == 0: # base case

return 1
else:
return n * factorial(n-1)

# recursive case

print(factorial(5))
# 120

Recursive functions must always have a base case to avoid infinite recursion.

LAMBDA FUNCTIONS (Anonymous Functions)

• One-line functions without a name, created using lambda keyword.

• Syntax:

• lambda arguments: expression


• Example:
• square = lambda x: x*x

• print(square(5)) # 25

• Often used with functions like map(), filter(), reduce().

nums = [1, 2, 3, 4]

squares = list(map(lambda x: x*x, nums))

print(squares) # [1, 4, 9, 16]

Components of a Function
• Function Definition → specifies name, parameters, and body.

• Parameters → variables inside parentheses of the definition.

• Arguments → values passed while calling the function.

• Return statement → sends value back to caller.

• Function Call → invoking the function using its name.

Function Categories

Functions without arguments & without return value


def display():

print("Hello World")
display()
Functions with arguments but without return value

def greet(name):

print("Hello", name)

greet("john")
Functions without arguments but with return value

def pi_value():

return 3.14

print(pi_value())

Functions with arguments and return value

def add(a, b):

return a+b
print(add(5, 3))

Advantages of Functions

⚫ Reduces redundancy

⚫ Hides complexity

⚫ Makes code modular and structured

⚫ Easy debugging and maintenance

⚫ Promotes code reusability

Example Program

def factorial(n):

fact = 1

for i in range(1, n+1):

fact *= i

return fact

num = 5
print("Factorial of", num, "is", factorial(num))
8. Summary Table

Feature Description

Definition Block of reusable code

Types Built-in, User-defined

Syntax def name(parameters): ... return value

Parameters Variables in function definition

Arguments Values passed during function call

Return Sends result back

Advantages Reusability, modularity, readability, debugging

Return Values

• A function can return a value to the caller using the return statement.

• If no return is used, function automatically returns None.

• A function can return:


o A single value

o Multiple values (as tuple)

o No value (None)

Example: Single Value

def square(n):
return n*n

print(square(4)) # 16

Example: Multiple Values


def calc(a, b):

return a+b, a-b, a*b

res = calc(5, 2)

print(res) # (7, 3, 10)


Example: No Return
def greet():

print("Hello")

result = greet() # Output: Hello

print(result) # None

4. Difference Between Arguments and Return Values

Feature Arguments Return Values

Definition Data passed into a function Data sent out of a function

Direction Caller → Function Function → Caller

Keyword Used Passed inside () Returned using return

Example add(5,7) → 5,7 are arguments return a+b sends result back

Formal vs. Actual Arguments

When using functions in Python:

• Parameters → act as placeholders inside the function definition.


• Arguments → are the real values passed while calling the function.

Thus, arguments are of two types:

1. Formal Arguments

2. Actual Arguments

Formal Arguments
• Variables defined in the function header.

• Receive the values from the function call.


• Exist only inside the function (local scope).

Example

def add(a, b): # a, b are formal arguments

return a + b
Here, a and b are formal arguments.
Actual Arguments

• Values or variables passed to the function during the call.

• These are assigned to the formal arguments.

Example
sum1 = add(10, 20) # 10, 20 are actual arguments

Here, 10 and 20 are actual arguments.

Key Difference Table

Aspect Formal Arguments Actual Arguments

Definition Variables in function definition Values/variables in function call

Where Declared Inside function header Inside function call

Purpose Receive data Provide data

Scope Local to function Exist in calling program

Example def add(a, b): → a, b add(5, 7) → 5, 7

Example Program

def multiply(x, y): # x, y → formal arguments

return x * y

result = multiply(4, 3) # 4, 3 → actual arguments

print("Result:", result)

Output:
Result: 12

Named Arguments:

Definition

• Named arguments (also called keyword arguments) are arguments passed to a


function using the parameter names.
• The order of arguments does not matter, since Python matches them by name.

Syntax
function_name(parameter1=value1, parameter2=value2, ...)

Example

def student(name, age, dept):

print("Name:", name)
print("Age:", age)

print("Department:", dept)

# Using named (keyword) arguments

student(age=20, dept="CSE", name="Meena")

Output:

Name: Meena

Age: 20
Department: CSE
Order does not matter because arguments are matched by name.

Advantages of Named Arguments

• Clarity: Increases readability of function calls.

• Flexibility: Order of arguments can be changed.

• Avoids Errors: Prevents confusion when many parameters exist.

• Optional Usage: Can mix positional and keyword arguments (positional must come
first).

Mixed Example (Positional + Named)

def order(item, qty, price):

print(qty, "x", item, "costs", qty*price)

# Mix of positional and named

order("Pen", price=10, qty=5)

Output:

5 x Pen costs 50
Rule

• Positional arguments must appear before named arguments in a function call.

# Valid

order("Book", qty=2, price=100)

# Invalid

order(item="Book", 2, 100) # Error

Recursive Functions and Lambda Functions

1. Recursive Functions
Definition

• A recursive function is a function that calls itself directly or indirectly.

• Every recursive function must have:

1. Base Case → condition to stop recursion.

2. Recursive Case → function calls itself with a smaller subproblem.

Syntax
def function_name(parameters):

if base_condition:

return value

else:

return function_name(modified_parameters)

Example: Factorial of a Number


def factorial(n):

if n == 0: # Base Case

return 1

else: # Recursive Case


return n * factorial(n-1)
print(factorial(5)) # 120

Example: Fibonacci Series

def fib(n):
if n <= 1:

return n

else:

return fib(n-1) + fib(n-2)

for i in range(6):

print(fib(i), end=" ")

Output: 0 1 1 2 3 5

Advantages

⚫ Reduces code length

⚫ Natural fit for problems like factorial, Fibonacci, tree traversal

Disadvantages

⚫ May cause stack overflow if base case is missing

⚫ Slower for large inputs (uses more memory & function calls)

Lambda Functions

Definition

• Lambda functions are anonymous (nameless) one-line functions.

• Defined using the keyword lambda.

• Used for short, simple operations.

Syntax
lambda arguments : expression

Example 1: Square of a Number


square = lambda x: x * x
print(square(5)) # 25

Example 2: Sum of Two Numbers

add = lambda a, b:

a+b
print(add(3, 7))

# 10

Example 3: Using with map(), filter(), reduce()

nums = [1, 2, 3, 4, 5]

# map() → apply lambda to each element

squares = list(map(lambda x: x*x, nums))


print(squares) # [1, 4, 9, 16, 25]
# filter() → filter even numbers

evens = list(filter(lambda x: x%2==0, nums))

print(evens) # [2, 4]

Advantages

Short & concise functions


Useful in functional programming (map, filter, reduce)
Can be used where a function is required temporarily

Limitations

Limited to single expression


Less readable for complex logic

3. Quick Comparison Table

Feature Recursive Function Lambda Function

Definition Function calling itself Anonymous single-line function

Purpose Solve problems by breaking down Perform small tasks quickly

Has Name? Yes (defined with def) No (defined with lambda)


Feature Recursive Function Lambda Function

Structure Can have multiple lines, base case Single expression only

Example factorial(n) lambda x: x*x

• A recursive function is one that calls itself to solve smaller instances of a problem
until a base case is reached.

• A lambda function is an anonymous, single-expression function created using the


lambda keyword, useful for short operations.

You might also like