[go: up one dir, main page]

0% found this document useful (0 votes)
8 views20 pages

2.4 Functions

This document provides an overview of functions in programming, specifically in Python, detailing their definition, components, and various types such as functions with parameters, default arguments, return values, and lambda functions. It explains the behavior of mutable and immutable objects when passed as arguments, emphasizing the importance of understanding object references. Additionally, it includes examples to illustrate the concepts discussed.

Uploaded by

Bhargav Rajyagor
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)
8 views20 pages

2.4 Functions

This document provides an overview of functions in programming, specifically in Python, detailing their definition, components, and various types such as functions with parameters, default arguments, return values, and lambda functions. It explains the behavior of mutable and immutable objects when passed as arguments, emphasizing the importance of understanding object references. Additionally, it includes examples to illustrate the concepts discussed.

Uploaded by

Bhargav Rajyagor
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/ 20

Unit – 2

Programming Basics
2.4 Functions
INTRODUCTION

A function is a collection of statements grouped together that


performs an operation.

Functions can be used to define reusable code and organize and


simplify code.

2
Defining a Function
def function_name(parameters):

"""

Docstring: Optional description of the function.

"""

# Function body: Code block containing the statements that define the function's
behavior.

# ...

# Optionally, the function can return a value using the 'return' statement.

return result 3
Defining a Function
Here's a breakdown of each component:
def: This keyword is used to define a function.
function_name: The name of the function, which follows the standard Python variable
naming rules.
parameters: A comma-separated list of input parameters (arguments) that the function
accepts. These are optional, and a function can have no parameters or multiple
parameters.
Docstring: An optional string at the beginning of the function definition that provides
documentation and describes what the function does.
Function body: The block of code containing the statements that define the function's
behavior. This is indented under the def line.
return: An optional statement used to return a value from the function. If the return
statement is omitted, the function returns None by default.

4
Functions without Parameters

These functions don't take any input parameters.


They are used when you need to encapsulate a block of code that doesn't require
external input.
def greet():
print("Hello, world!")

5
Functions with Parameters

These functions take one or more input parameters, allowing you to pass
values to them when calling the function.
def add_numbers(a, b):
return a + b

6
Functions with Default Arguments

You can provide default values for function parameters, making some or all of them
optional when calling the function.
def greet(name="User"):
#print("Hello," + name +"!")
print(f"Hello,{name} !")
greet("Aamin")

7
Functions with Return Values

These functions return a value or a result after performing some


operations. The return statement is used to specify what to return.
def multiply(a, b):
return a * b

ans = multiply(5,10)
print(ans)

Output :
50

8
Functions with Multiple Return Values

Python functions can return multiple values as a tuple, which can be


unpacked when calling the function
def get_name_and_age():
name = input("Enter name ::")
age = input("Enter age ::")
return name,age

name, age = get_name_and_age()


print(f"{name}'s age is :: {age}")

9
Recursive Functions

Recursive functions call themselves either directly or indirectly. They are often
used for tasks that can be broken down into smaller, similar sub-tasks.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
ans = factorial(5)
print(ans)

Output :
120
10
Passing arguments by reference values

In Python, all function arguments are passed by object reference.


However, this does not mean that Python uses "pass-by-reference" in
the same way as some other programming languages.

It's important to understand how Python's object references work to


avoid confusion.

11
Passing arguments by reference values

Immutable Objects: When you pass immutable objects like numbers, strings, and
tuples to a function, changes made to the parameter within the function do not affect the
original object. This behavior is similar to "pass-by-value" in other languages.

def modify_string(s):
s = s + " World" # This doesn't change the original string

greeting = "Hello"
modify_string(greeting)
print(greeting) # Output: "Hello"

12
Passing arguments by reference values

Mutable Objects: When you pass mutable objects like lists, dictionaries, or custom
objects to a function, changes made to the parameter within the function do affect the
original object. This behavior is similar to "pass-by-reference" in other languages.
def modify_list(my_list):
my_list.append(4) # This changes the original list

numbers = [1, 2, 3]
modify_list(numbers)
print(numbers) # Output: [1, 2, 3, 4]

13
Passing arguments by reference values

So, whether a function affects the original object or not depends on whether the
object is mutable or immutable. Immutable objects are effectively passed by value,
while mutable objects are effectively passed by reference.

Keep in mind that even though you can modify mutable objects within a function,
it's generally a good practice to avoid side effects and return modified values
explicitly. This helps improve the clarity and maintainability of your code.

14
Lambda Functions

Lambda functions, also known as anonymous functions or lambda expressions, are a way
to create small, simple, and unnamed functions in Python.

They are typically used for short, one-time operations where a full function definition is
not required.

Lambda functions are defined using the lambda keyword, followed by the input
parameters and an expression that defines the function's behavior.

15
Basic syntax of a lambda function:

lambda arguments: expression


Key points to remember about lambda functions:
Anonymous: Lambda functions are anonymous because they don't have a name like regular functions defined using the
def keyword.

Single Expression: Lambda functions can only consist of a single expression, which is evaluated and
returned as the result of the function.

No Statements: Lambda functions cannot contain statements, assignments, or multiple expressions.


They are limited to a single, concise expression.

Concise: Lambda functions are most useful when the function logic is simple and can be expressed in a
single line of code.

Functional Programming: They are often used in functional programming constructs like map, filter,
and reduce.

16
Examples of lambda functions

# Example 1: A lambda function that adds two numbers


add = lambda x, y: x + y
result = add(3, 5) # result will be 8
print(result)

# Example 2: A lambda function to square a number


square = lambda x: x ** 2
result = square(4) # result will be 16
print(result
17
Examples of lambda functions

# Example 3: Using lambda with built-in functions like sorted


names = ["Alice", "Bob", "Charlie", "David"]
sorted_names = sorted(names, key=lambda name: len(name))
# sorted_names will be ["Bob", "Alice", "David", "Charlie"]
print(sorted_names)

Output:
['Bob', 'Alice', 'David', 'Charlie']

18
Lambda functions

Lambda functions are particularly handy in cases where you need to pass a
small, one-time function as an argument to another function or method, like
when sorting a list or filtering elements.

However, for more complex or reusable functions, it's generally better to define
regular functions using the def keyword, as they provide better readability and
maintainability.

19
Thanks

You might also like