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

Unit 4 Python Functions

Uploaded by

utsavsutariya066
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
20 views15 pages

Unit 4 Python Functions

Uploaded by

utsavsutariya066
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 15

Unit 4 Python Functions

4.1 Function Basics

A function is a block of code which only runs when it is


called.

You can pass data, known as parameters, into a


function.

A function can return data as a result.

Creating a Function

In Python a function is defined using the def keyword:

Example
def my_function():
print("Hello from a function")

• Built-in library function: These are Standard


functions in Python that are available to use.
• User-defined function: We can create our own
functions based on our requirements.

EXAMPLE
ef add(num1: int, num2: int) -> int:
"""Add two numbers"""
num3 = num1 + num2

return num3

# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results
{ans}.")

Output:
The addition of 5 and 15 results 20.

4.1.1 Definition, Call, Passing Arguments


Definition:
In programming, a function is a block of reusable code that
performs a specific task. It can take input, process it, and return
output (if necessary).
Call:
To use a function, you must call it by its name followed by
parentheses (). For example, to call a function named
"my_function," you would write "my_function()" in your code.

Passing Arguments:
Functions can also accept input in the form of arguments.
Arguments are values or variables that are passed into the
function to be used during its execution. To pass arguments to
a function, you simply include them in the parentheses when
calling the function. For example, if you have a function that
takes two arguments called "add_numbers," you would call it
like this: "add_numbers(3, 4)". In this case, the function would
add 3 and 4 together and return the result.

4.1.2 Lambda Functions


A lambda function is a small anonymous function.

A lambda function can take any number of arguments,


but can only have one expression.

in the example above, the expression is composed of:

• The keyword: lambda


• A bound variable: x
• A body: x
Example

numbers = [1, 2, 3, 4]

doubled_numbers = map(lambda x: x * 2, numbers)

print(list(doubled_numbers))

# Output: [2, 4, 6, 8]

Why Use Lambda Functions?


The power of lambda is better shown when you use
them as an anonymous function inside another
function.

Say you have a function definition that takes one


argument, and that argument will be multiplied with an
unknown number:

def myfunc(n):
return lambda a : a * n

Anonymous Functions
• Lambda functions
• Lambda expressions
• Lambda abstractions
• Lambda form

4.2 Function Parameter and Call


Function
A function is a block of code which only runs when it is
called.

You can pass data, known as parameters, into a


function.

A function can return data as a result.

Creating a Function

In Python a function is defined using the def keyword:

Example

def my_function():
print("Hello from a function")

• Built-in library function: These are Standard


functions in Python that are available to use.

• User-defined function: We can create our own


functions based on our requirements.
Parameter
To pass information to any function, we use some variables or
objects known as parameters. The function processes this
information and returns the result.

Generally, there are two types of parameters in Python. They


are

• Formal parameters
• Actual parameters
Syntax
• def function_name(formal_parameters): #function
definition
• #statements

• function_name(actual_parameters) #function call

• Formal parameters
• The parenthesis of function definition consists of variables
known as formal parameters. The information of the actual
parameters gets copied into these formal parameters
when a function gets called.
• EXAMPLE
• def add(a,b): #function definition
• return a+b

• Actual parameters
In python, the actual parameters are also known as Arguments.
The arguments are the data or objects specified during a
function call. It passes the data to the function where the formal
parameters capture the data and copies into them.

There are 4 types of arguments in Python. They are:

• Default arguments
• Required arguments
• Keyword arguments
• Arbitrary arguments
Let us understand them clearly in an easy way.

4.2.1 Calling value returning function


o call a value-returning function in Python, you can follow these
steps:

1. Define the function: Define a function that takes some


input arguments, performs some operation, and returns a
value as the output.

For example, here is a simple function that adds two numbers


and returns the result:

def add_numbers(x, y):


return x + y
2. Call the function: To call the function, write its name
followed by parentheses with any required arguments
inside them. Assign the return value to a variable or use it
in an expression.
For example, you can call the "add_numbers" function and
assign its return value to a variable like this:

result = add_numbers(3, 4)
print(result)
# Output: 7
4.2.2 Calling non-value returning function
To call a non-value returning function in Python, you can follow
these steps:

1. Define the function: Define a function that takes some input


arguments, performs some operation, and doesn't return any
value.

For example, here is a simple function that prints a greeting


message:

```
def say_hello(name):
print("Hello, " + name + "!")
```

2. Call the function: To call the function, write its name followed
by parentheses with any required arguments inside them.

For example, you can call the "say_hello" function like this:
```
say_hello("Alice") # Output: Hello, Alice!
```

In this example, the function "say_hello" is called with the string


"Alice", which is passed to the "name" parameter. The function
prints a greeting message to the console.

Remember to use the correct number and type of arguments


when calling a function, otherwise, you may get a TypeError or
unexpected results.

Note that since a non-value returning function doesn't return


any value, you cannot assign its output to a variable or use it in
an expression. It is mainly used to perform some actions or
operations that don't require a return value.

4.2.3 Parameter Passing


Parameter passing is the process of passing data or arguments to a
subroutine or function in a programming language. When a
subroutine or function is called, it requires information to perform its
task, which is provided through input parameters or arguments.

The two main methods of parameter passing are called pass-by-value


and pass-by-reference. When using pass-by-value, the function
receives a copy of the values of the parameters, so any changes
made to them inside the function do not affect the original values. In
pass-by-reference, the function receives a reference to the variables
passed as arguments, so any changes made to them inside the
function are reflected in the original values.

The choice of which parameter passing method to use can have


significant impacts on program efficiency, memory usage, and
readability. It is important for programmers to carefully consider
which method is appropriate for the specific programming task at
hand.

4.2.4 Function arguments and variable scope


Function arguments
Default Arguments in Python
• Default arguments are values that are provided while defining
functions.
• The assignment operator = is used to assign a default value to
the argument.
• Default arguments become optional during the function calls.
• If we provide a value to the default arguments during function
calls, it overrides the default value.
• The function can have any number of default arguments.
• Default arguments should follow non-default arguments.

Example
def add(a,b=5,c=10):
return (a+b+c)

Keyword Arguments in Python


Functions can also be called using keyword arguments of the form
kwarg=value.
During a function call, values passed through arguments don’t need to
be in the order of parameters in the function definition. This can be
achieved by keyword arguments. But all the keyword arguments
should match the parameters in the function definition.
def add(a,b=5,c=10):
return (a+b+c)

Positional Arguments in Python(variable-length)


During a function call, values passed through arguments should be in
the order of parameters in the function definition. This is called
positional arguments.

Keyword arguments should follow positional arguments only.


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

Required arguments

• Required arguments are the arguments passed to a function


in correct positional order.
• The number of arguments in the function call should match
exactly with the function
definition.
EXAMPLE

# Function definition is here


def printme( name, age ):
"This prints a passed string into this function"
print (name , age)
# Now you can call printme function
printme("Ajay",30)
4.2.4 Function arguments and variable scope
variable scope

The location where we can find a variable and also access it if


required is called the scope of a variable.

Python Local variable

Local variables are those that are initialized within a function and are
unique to that function. It cannot be accessed outside of the function.
Let’s look at how to make a local variable.

def f():

# local variable
s = "I love Geeksforgeeks"
print(s)

# Driver code
f()
Python Global variables

Global variables are the ones that are defined and declared outside
any function and are not specified to any function. They can be used
by any part of the program.

# This function uses global variable s


def f():
print(s)

# Global scope
s = "I love Geeksforgeeks"
f()

Global and Local Variables with the Same Name

Now suppose a variable with the same name is defined inside the
scope of the function as well then it will print the value given inside
the function only and not the global value.

EXAMPLE

# This function has a variable with


# name same as s.
def f():
s = "Me too."
print(s)

# Global scope
s = "I love Geeksforgeeks"
f()
print(s)

You might also like