0% found this document useful (0 votes)
6 views3 pages

Function in Python

This document explains the concept of functions in Python, highlighting their definition, parameters, return values, and benefits such as reusability and organization. It also covers lambda functions, their syntax, limitations, and practical applications with built-in functions like filter(), map(), and reduce(). Additionally, it provides examples and exercises for creating and using both regular and lambda functions.

Uploaded by

rsingh.csed.cf
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)
6 views3 pages

Function in Python

This document explains the concept of functions in Python, highlighting their definition, parameters, return values, and benefits such as reusability and organization. It also covers lambda functions, their syntax, limitations, and practical applications with built-in functions like filter(), map(), and reduce(). Additionally, it provides examples and exercises for creating and using both regular and lambda functions.

Uploaded by

rsingh.csed.cf
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

FUNCTION IN PYTHON

A function is a reusable block of code that performs a specific task. Functions allow you to structure your
code in a more organized and modular way, which makes it easier to maintain and debug.

KEY POINTS:

• Function definition: You define a function with def.


• Parameters: Functions can take parameters, which allow you to pass data to them.
• Return value: Functions can return a value using return. This value can be used later in your program.
• Function call: To execute the function, you use the function name followed by parentheses () with
any necessary arguments.
BENEFITS OF USING FUNCTIONS:

1. Reusability: Once a function is defined, you can reuse it multiple times without rewriting the code.
2. Organization: Functions help to break down a program into smaller, more manageable pieces.
3. Debugging: Functions make it easier to find and fix bugs since you can isolate parts of the code.
4. Readability: By using functions, you make your code more readable and understandable for others
(or yourself) who will maintain it in the future.
BASIC SYNTAX:

def function_name(parameters):
# code to execute
return result
• def is the keyword used to define a function.
• function_name is the name you give to the function. It should follow standard naming conventions
(letters, numbers, and underscores).
• parameters (optional) are values you can pass into the function when calling it.
• The return statement is optional. If included, it allows the function to send a value back to the caller.

Example 1: Simple Function Example 2: Function with Parameters


def greet(): def greet(name):
print("Hello, World!") print(f"Hello, {name}!")
greet() # Calling the function greet("Alice") # Calling with an argument

Example 3: Function with Return Value Example 4: Default Function


def add(a, b): def greet(name="Guest"):
return a + b print(f"Hello, {name}!")
result = add(3, 4) # Function call returns a value greet() # Output: Hello, Guest!
print(result) # Output will be 7 greet("Alice") # Output: Hello, Alice!

LAMBDA FUNCTIONS IN PYTHON


A lambda function is a small, anonymous function defined with the keyword lambda. Lambda functions are
typically used for short, throwaway functions that are not going to be reused elsewhere in the code.

• A lambda function is a one-line function that can accept multiple arguments, but it can only have
one expression.
• It can be passed as an argument to higher-order functions like map(), filter(), and sorted().
Syntax: lambda arguments: expression
add = lambda x, y: x + y
print(add(2, 3)) # Output: 5
• lambda: Keyword that signifies a lambda function.
• arguments: A comma-separated list of parameters the function will accept (can be zero or more).
• expression: A single expression that is evaluated and returned when the function is called.

Ex: Simple Lambda Function with One Argument Ex: Lambda Function with Multiple Arguments
# A lambda function that squares its input # A lambda function that adds two numbers
square = lambda x: x ** 2 add = lambda x, y: x + y
print(square(5)) # Output: 25 print(add(3, 4)) # Output: 7

Ex: Lambda Function with No Arguments


#lambda function that returns a constant value
get_five = lambda: 5
print(get_five()) # Output: 5

LIMITATIONS OF LAMBDA FUNCTIONS


1. Limited to One Expression: Lambda functions can only have a single expression. They are not suitable
for complex logic or multiple statements.
2. Hard to Debug: Because lambda functions do not have names and are often written in one line,
debugging can be more difficult compared to regular functions.
3. Not Always Readable: Although lambda functions are concise, they can sometimes reduce code
readability, especially for those not familiar with the syntax.

LAMBDA FUNCTIONS IN ACTION

In Python, filter(), map(), and reduce() are built-in functions that allow you to process iterables (like lists,
tuples, etc.) in a functional programming style. They can be very useful for applying a function to each item
of an iterable, filtering elements, or reducing the iterable to a single value.

1. filter() function : Filters elements from an iterable based on a condition

The filter() function is used to filter elements from an iterable (like a list, tuple, etc.) based on a condition. It
takes two arguments:

• A function that returns True or False for each item in the iterable (typically a lambda function).
• An iterable (like a list or tuple) to filter.
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6]

2. map() function : Applies a function to each item in an iterable and returns a new iterable.

The map() function applies a given function to each item in an iterable (like a list or tuple). It returns an
iterator that produces the result of applying the function to each item in the iterable. It takes two
arguments:
• A function to apply to each item (like a lambda function).
• An iterable to apply the function to.
You often need to convert the result into a list or another iterable type to view the output.
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16, 25]

3. reduce() function : Cumulatively applies a function to reduce an iterable to a single value.


The reduce() function is part of the functools module, and it's used to apply a binary function (a function
that takes two arguments) cumulatively to the items in an iterable. It reduces the iterable to a single value.
It takes two arguments:
• A function that takes two arguments (typically a lambda function).
• An iterable to process.
You need to import reduce() from the functools module.
from functools import reduce

numbers = [1, 2, 3, 4, 5]
sum_of_numbers = reduce(lambda x, y: x + y, numbers)
print(sum_of_numbers) # Output: 15

4. sorted() function: The sorted() function can take a key function, which can be defined with a lambda, to
sort iterables based on custom criteria.

students = [("Alice", 85), ("Bob", 72), ("Charlie", 91)]


# Sort students by their scores
sorted_students = sorted(students, key=lambda student: student[1])
print(sorted_students) # Output: [('Bob', 72), ('Alice', 85), ('Charlie', 91)]

o Write a function to calculate the factorial of a number.


o Write a function to find the maximum of three numbers.
o Write a function to count the number of vowels in a string.
o Write a function to calculate the Fibonacci sequence up to the nth number.

o Write a lambda function that returns the maximum of two numbers.


o Define a lambda function max_of_two(x, y) that returns the larger of x and y.

o Use lambda to filter even numbers from a list.


o Use lambda with map() to square each element in a list.
o Use reduce() and lambda to calculate the product of all elements in a list.
o Use map() and lambda to convert a list of strings to uppercase.

You might also like