KEMBAR78
Functions | PDF | Parameter (Computer Programming) | Recursion
0% found this document useful (0 votes)
2 views6 pages

Functions

This document provides an introduction to functions in Python, explaining their definition, purpose, and how to define and call them. It covers various types of functions, including built-in, user-defined, and lambda functions, as well as the concepts of parameters and arguments. Additionally, it discusses function composition, the return statement, and recursion, highlighting their advantages and disadvantages.

Uploaded by

saranya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views6 pages

Functions

This document provides an introduction to functions in Python, explaining their definition, purpose, and how to define and call them. It covers various types of functions, including built-in, user-defined, and lambda functions, as well as the concepts of parameters and arguments. Additionally, it discusses function composition, the return statement, and recursion, highlighting their advantages and disadvantages.

Uploaded by

saranya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

UNIT III

Introduction to Functions in Python

Functions in Python are blocks of reusable code that perform a specific task. Instead of
writing the same code again and again, you define a function once and use it whenever
needed.

Why Use Functions?

 Reusability: Write once, use many times.


 Organization: Break a program into smaller, manageable parts.
 Readability: Code is cleaner and easier to understand.
 Debugging: Easier to test and fix bugs in small pieces of code.

How to Define a Function

def function_name(parameters):
return result
Example:
def greet(name):
print("Hello,", name)
This defines a function called greet that takes one parameter, name, and prints a greeting.

How to Call a Function


You call a function by using its name followed by parentheses:
greet("Alice")
# Output: Hello, Alice

Function with Return Value


def add(a, b):
return a + b
result = add(3, 5)
print(result) # Output: 8

Types of Functions
1. Built-in functions – e.g., print(), len(), type()
2. User-defined functions – functions you create using def
3. Lambda functions – short, anonymous functions (advanced topic)

Built-in Functions in Python

Python comes with many built-in functions that you can use without importing any
library. These functions help you perform common tasks like:

 Working with numbers and strings


 Handling input/output
 Performing type conversions
 Managing data structures like lists, tuples, and dictionaries

Most Common Built-in Functions


Function Description Example
print() Displays output print("Hello")
len() Returns the length of a sequence len("Python") → 6
type() Returns the type of an object type(10) → <class 'int'>
input() Takes input from the user name = input("Enter name: ")
int(), float(), str() Converts between types int("10") → 10
max() / min() Finds max/min of values max(1, 5, 3) → 5
sum() Adds items in an iterable sum([1, 2, 3]) → 6
sorted() Returns a sorted list sorted([3, 1, 2]) → [1, 2, 3]
range() Generates a range of numbers range(5) → 0 1 2 3 4
abs() Absolute value abs(-7) → 7
round() Rounds a number round(4.67) → 5
enumerate() Adds counter to iterable enumerate(['a','b'])

Example: Using Built-in Functions

numbers = [5, 3, 8, 1]
print("Length:", len(numbers)) # Output: 4
print("Maximum:", max(numbers)) # Output: 8
print("Sorted:", sorted(numbers)) # Output: [1, 3, 5, 8]
print("Sum:", sum(numbers)) # Output: 17

Composition of Functions in Python


Function composition means combining two or more functions so that the output of one
function becomes the input of another.This concept helps build more powerful and
modular code by chaining simple functions together.

Basic Example

Suppose you have two functions:

def square(x):
return x * x

def double(x):
return x * 2

You can compose them manually:

result = double(square(3)) # square(3) = 9 → double(9) = 18

print(result) # Output: 18

In this example, square(3) is computed first, then double(9).

General Syntax of Function Composition

f(g(x))

 g(x) runs first.


 The result of g(x) is passed into f().
Why Use Function Composition?

 Reduces repetition
 Makes code modular and easier to test
 Promotes code reuse and readability

Parameters vs Arguments in Python Functions

These two terms are often confused, but they mean different things:

PARAMETERS

 Definition: Variables listed inside the parentheses in a function definition.


 Purpose: They act as placeholders for values the function will receive when it's
called.

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


print("Hello,", name)

Here, name is a parameter.

ARGUMENTS

 Definition: The actual values passed to the function when it is called.


 Purpose: These values replace the parameters when the function runs.

greet("Alice") # ← 'Alice' is an argument

Here, "Alice" is an argument passed into the function.

Simple Analogy

Parameters are like variable names in a recipe (e.g., ingredient1),


Arguments are the actual items you use when cooking (e.g., sugar, flour).

Example with Multiple Parameters

def add(a, b): # a and b are parameters


return a + b

result = add(3, 5) # 3 and 5 are arguments


print(result) # Output: 8

Types of Arguments in Python

1. Positional arguments
o Matched by position/order

def greet(name, age):


print(f"Name: {name}, Age: {age}")

greet("Bob", 25)

2. Keyword arguments
o Matched by name

greet(age=25, name="Bob")

3. Default arguments
o Parameter has a default value if not provided

def greet(name="Guest"):
print("Hello,", name)

greet() # Output: Hello, Guest


greet("Alice") # Output: Hello, Alice

RETURN STATEMENT IN PYTHON

The return statement in Python is used inside a function to:

 Send a value back to the caller (the place where the function was called).
 Exit the function immediately when it is reached.

Basic Syntax

def function_name(parameters):

return value

Example: Returning a Single Value

def add(a, b):


return a + b

result = add(3, 5)
print(result) # Output: 8

The function returns 8, which is stored in result.

A function without return

If you don’t use return, the function returns None by default.

def greet(name):
print("Hello", name)

result = greet("Alice")
print(result) # Output: Hello Alice \n None

Returning Multiple Values

You can return multiple values as a tuple:

def calculate(a, b):


return a + b, a * b
sum_result, product_result = calculate(2, 3)
print(sum_result) # Output: 5
print(product_result) # Output: 6

PYTHON RECURSIVE FUNCTION

In Python, functions are reusable blocks of code that perform specific tasks, while
recursion is a technique where a function calls itself to solve problems by breaking them
down into smaller, manageable parts..

Understanding Functions in Python

Definition: A function is a named block of code designed to perform a specific task. Functions help
in organizing code, making it reusable and easier to read.

Syntax: Functions are defined using the def keyword, followed by the function name and
parentheses. For example:

def greet(name):

return f"Hello, {name}!"

Calling Functions: Once defined, a function can be called by its name followed by parentheses,
passing any required arguments:

print(greet("Alice")) # Output: Hello, Alice!

What is Recursion?

Definition: Recursion is a programming technique where a function calls itself to solve a


problem. It is particularly useful for problems that can be divided into similar subproblems,
such as calculating factorials or traversing tree structures.

Components:

Base Case: This is the condition under which the recursion stops. It prevents infinite loops. For
example, in a factorial function, the base case is when the input is 1.

Recursive Case: This part of the function includes the call to itself, reducing the problem
size with each call.

Example of Recursion: Factorial Function

Here’s a simple example of a recursive function to calculate the factorial of a number:

def factorial(n):
if n == 1: # Base case

return 1

else: # Recursive case

return n * factorial(n - 1)

ADVANTAGES AND DISADVANTAGES OF RECURSION

Advantages:

Simplicity: Recursive solutions can be more intuitive and easier to implement for
problems that are naturally recursive, such as tree traversals.

Reduced Code Length: Recursion can lead to shorter and cleaner code compared to iterative
solutions.

Disadvantages:

Memory Overhead: Each recursive call adds a new layer to the stack, which can lead to
high memory usage and potential stack overflow errors for deep recursion.

Performance Issues: Recursive functions may be slower due to the overhead of multiple
function calls.

EXAMPLE PROGRAM
def factorial(n):
if n == 0: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive case
print(factorial(5)) # Output: 120

You might also like