[Go to site: main page, start]

100% found this document useful (1 vote)
113 views12 pages

Overview of Python Functions

In Python, functions can be called by either call by value or call by reference depending on the arguments passed. Call by value passes the value of an argument which is immutable, so any changes inside the function aren't reflected outside. Call by reference passes the reference to mutable arguments, so changes inside the function are reflected outside since the argument is modified in place. Lambda functions are anonymous functions that can be used wherever function objects are needed, such as with built-in functions like filter() and map().

Uploaded by

Arshdeep Singh
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
100% found this document useful (1 vote)
113 views12 pages

Overview of Python Functions

In Python, functions can be called by either call by value or call by reference depending on the arguments passed. Call by value passes the value of an argument which is immutable, so any changes inside the function aren't reflected outside. Call by reference passes the reference to mutable arguments, so changes inside the function are reflected outside since the argument is modified in place. Lambda functions are anonymous functions that can be used wherever function objects are needed, such as with built-in functions like filter() and map().

Uploaded by

Arshdeep Singh
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

What is a function in Python?

In Python, a function is a group of related statements that performs a specific task.

Functions help break our program into smaller and modular chunks. As our program
grows larger and larger, functions make it more organized and manageable.

Furthermore, it avoids repetition and makes the code reusable.

Syntax of Function

def function_name(parameters):

"""docstring"""

statement(s)

Above shown is a function definition that consists of the following components.

[Link]  def  that marks the start of the function header.


2.A function name to uniquely identify the function. Function naming follows the
same rules of writing identifiers in Python.
[Link] (arguments) through which we pass values to a function. They are optional.

4.A colon (:) to mark the end of the function header.

[Link] documentation string (docstring) to describe what the function does.

[Link] or more valid python statements that make up the function body. Statements must
have the same indentation level (usually 4 spaces).
[Link] optional  return  statement to return a value from the function.
Example of a function

def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")

How to call a function in python?

Once we have defined a function, we can call it from another function, program, or even
the Python prompt. To call a function we simply type the function name with appropriate
parameters.

>>> greet('Paul')
Hello, Paul. Good morning!

Try running the above code in the Python program with the function definition to see the
output.

def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")

greet('Paul')
Run Code

Note : In python, the function definition should always be present before the

function call. Otherwise, we will get an error. For example,

# function call
greet('Paul')

# function definition
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
# Error: name 'greet' is not defined

Python Recursion
In this tutorial, you will learn to create a recursive function (a function that calls itself).

What is recursion?
Recursion is the process of defining something in terms of itself.

A physical world example would be to place two parallel mirrors facing each other. Any
object in between them would be reflected recursively.

Python Recursive Function


In Python, we know that a function can call other functions. It is even possible for the
function to call itself. These types of construct are termed as recursive functions.
The following image shows the working of a recursive function called  recurse .

Recursive Function in Python

Following is an example of a recursive function to find the factorial of an integer.

Factorial of a number is the product of all the integers from 1 to that number. For
example, the factorial of 6 (denoted as 6!) is  1*2*3*4*5*6 = 720 .
Example of a recursive function
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""

if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
Run Code

Output

The factorial of 3 is 6

Python Anonymous/Lambda Function


In this article, you'll learn about the anonymous function, also known as lambda
functions. You'll learn what they are, their syntax and how to use them (with examples).

What are lambda functions in Python?


In Python, an anonymous function is a function that is defined without a name.
While normal functions are defined using the  def  keyword in Python, anonymous
functions are defined using the  lambda  keyword.
Hence, anonymous functions are also called lambda functions.

How to use lambda Functions in Python?


A lambda function in python has the following syntax.

Syntax of Lambda Function in python

lambda arguments: expression

Lambda functions can have any number of arguments but only one expression. The
expression is evaluated and returned. Lambda functions can be used wherever function
objects are required.

Example of Lambda Function in python

Here is an example of lambda function that doubles the input value.


# Program to show the use of lambda functions
double = lambda x: x * 2

print(double(5))
Run Code

Output

10

In the above program,  lambda x: x * 2  is the lambda function. Here  x  is the argument and  x
* 2  is the expression that gets evaluated and returned.
This function has no name. It returns a function object which is assigned to the
identifier  double . We can now call it as a normal function. The statement

double = lambda x: x * 2

is nearly the same as:

def double(x):

return x * 2

Use of Lambda Function in python


We use lambda functions when we require a nameless function for a short period of time.

In Python, we generally use it as an argument to a higher-order function (a function that


takes in other functions as arguments). Lambda functions are used along with built-in
functions like  filter() ,  map()  etc.
Example use with filter()
The  filter()  function in Python takes in a function and a list as arguments.
The function is called with all the items in the list and a new list is returned which
contains items for which the function evaluates to  True .
Here is an example use of  filter()  function to filter out only even numbers from a list.
# Program to filter out only the even items from a list
my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(filter(lambda x: (x%2 == 0) , my_list))

print(new_list)
Run Code
Output

[4, 6, 8, 12]

Example use with map()


The  map()  function in Python takes in a function and a list.

The function is called with all the items in the list and a new list is returned which contains items
returned by that function for each item.
Here is an example use of  map()  function to double all the items in a list.
# Program to double each item in a list using map()

my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(map(lambda x: x * 2 , my_list))

print(new_list)
Run Code

Output

[2, 10, 8, 12, 16, 22, 6, 24]

Python call by reference or call by value


Pythonutilizes a system, which is known as “Call by Object Reference” or “Call by
assignment”. In the event that you pass arguments like whole numbers, strings or tuples to a
function, the passing is like call-by-value because you can not change the value of the
immutable objects being passed to the function. Whereas passing mutable objects can be
considered as call by reference because when their values are changed inside the function,
then it will also be reflected outside the function.
Example 1:

 python3

# Python code to demonstrate


# call by value
 
 
string = "Geeks"
 
 
def test(string):
     
    string = "GeeksforGeeks"
    print("Inside Function:", string)
     
# Driver's code
test(string)
print("Outside Function:", string)

Output 
 
Inside Function: GeeksforGeeks

Outside Function: Geeks

Example 2

 Python3

# Python code to demonstrate


# call by reference
 
 
def add_more(list):
    [Link](50)
    print("Inside Function", list)
 
# Driver's code
mylist = [10,20,30,40]
 
add_more(mylist)
print("Outside Function:",
mylist)

Output 
 
Inside Function [10, 20, 30, 40, 50]

Outside Function: [10, 20, 30, 40, 50]


Difference between call by value and call by
reference in Python
Difference between call by value and call by reference in Python : In this tutorial, we will
study the call by value and call by reference in python programming. Python programming
language uses the mechanism of the call-by-object and also call by object reference. If you
pass the arguments like strings, tuples to function the passing values will act as the call by
value.

all by value Call by reference


Call by value:-The parameter values are copiedCall by reference:-
to function parameter and then two types of The actual, as well as the formal
parameters are stored in the memoryparameters refer to the same location
locations. and if changes are made inside the
When changes are made the functions are not functions the functions are reflected in
reflected in the parameter of the caller. the actual parameter of the caller.

While calling the function we pass values andAt the time of calling instead of passing
called as call by values. the values we pass the address of the
variables that means the location of
variables so called call by reference.
The value of each variable is calling the The address of variable in function while
function and copy variable into the variablescalling is copied into dummy variables of
of the function. a function.

The changes are made to dummy variables in By using the address we have the access
the called function that have no effect on the to the actual variable.
actual variable of the function.

We cannot change the values of the actual We can change the values of the actual
variable through a function call. variable through a function call.

The values are passed by the simple The pointers are necessary to define and
techniques store the address of variables.

Call by value Example:- Call by reference:-


def primtme (str):def changeme(mylist):
print [Link](1, 2, 3, 4]);
return; print”values inside the function:” mylist
printme(“I’m first call to user defined return
function!”) mylist= [10, 20, 30];
printme(“Again second call to same function”) changeme (mylist);
Output:- print”values outside the function:” mylist
I’m first call to user defined function! Output:-
Again second call to same function values inside the function: [10, 20, 30, [1, 2,
3, 4]]
values outside the function: [10, 20, 30, [1, 2,
3, 4]]

Python return keyword


A function is created to do a specific task. Often there is a result from such a task.
The return keyword is used to return values from a function. A function may or
may not return a value. If a function does not have a return keyword, it will
send None.

Python function definition


A function is a block of reusable code that is used to perform a specific action. The
advantages of using functions are:
Reducing duplication of code
Decomposing complex problems into simpler pieces
Improving clarity of the code
Reuse of code
Information hiding
Functions in Python are first-class citizens. It means that functions have equal
status with other objects in Python. Functions can be assigned to variables, stored
in collections, or passed as arguments. This brings additional flexibility to the
language.

Python User-defined Functions


In this tutorial, you will find the advantages of using user-defined functions and best
practices to follow.

What are user-defined functions in Python?


Functions that we define ourselves to do certain specific task are referred as user-defined
functions. The way in which we define and call functions in Python are already
discussed.
Functions that readily come with Python are called built-in functions. If we use functions
written by others in the form of library, it can be termed as library functions.

All the other functions that we write on our own fall under user-defined functions. So,
our user-defined function could be a library function to someone else.

Advantages of user-defined functions


1. User-defined functions help to decompose a large program into small segments which
makes program easy to understand, maintain and debug.

2. If repeated code occurs in a program. Function can be used to include those codes and
execute when needed by calling that function.

3. Programmars working on large project can divide the workload by making different
functions.

Example of a user-defined function


# Program to illustrate
# the use of user-defined functions
def add_numbers(x,y):
sum = x + y
return sum

num1 = 5
num2 = 6

print("The sum is", add_numbers(num1, num2))


Run Code

Output

Enter a number: 2.4


Enter another number: 6.5
The sum is 8.9

Python Built in Functions
❮ PreviousNext ❯

Python has a set of built-in functions.


Function Description
abs() Returns the absolute value of a number
all() Returns True if all items in an iterable object are true
any() Returns True if any item in an iterable object is true
Returns a readable version of an object. Replaces none-ascii characters with escape
ascii()
character
bin() Returns the binary version of a number
bool() Returns the boolean value of the specified object
bytearray() Returns an array of bytes
bytes() Returns a bytes object
callable() Returns True if the specified object is callable, otherwise False
chr() Returns a character from the specified Unicode code.
classmethod() Converts a method into a class method
compile() Returns the specified source as an object, ready to be executed
complex() Returns a complex number
delattr() Deletes the specified attribute (property or method) from the specified object
dict() Returns a dictionary (Array)
dir() Returns a list of the specified object's properties and methods
divmod() Returns the quotient and the remainder when argument1 is divided by argument2
enumerate() Takes a collection (e.g. a tuple) and returns it as an enumerate object
eval() Evaluates and executes an expression
exec() Executes the specified code (or object)
filter() Use a filter function to exclude items in an iterable object
float() Returns a floating point number
format() Formats a specified value
frozenset() Returns a frozenset object
getattr() Returns the value of the specified attribute (property or method)
globals() Returns the current global symbol table as a dictionary
hasattr() Returns True if the specified object has the specified attribute (property/method)
hash() Returns the hash value of a specified object
help() Executes the built-in help system
hex() Converts a number into a hexadecimal value
id() Returns the id of an object
input() Allowing user input
int() Returns an integer number
isinstance() Returns True if a specified object is an instance of a specified object
issubclass() Returns True if a specified class is a subclass of a specified object
iter() Returns an iterator object
len() Returns the length of an object
list() Returns a list
locals() Returns an updated dictionary of the current local symbol table
map() Returns the specified iterator with the specified function applied to each item
max() Returns the largest item in an iterable
memoryview() Returns a memory view object
min() Returns the smallest item in an iterable
next() Returns the next item in an iterable
object() Returns a new object
oct() Converts a number into an octal
open() Opens a file and returns a file object
ord() Convert an integer representing the Unicode of the specified character
pow() Returns the value of x to the power of y
print() Prints to the standard output device
property() Gets, sets, deletes a property
range() Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
repr() Returns a readable version of an object
reversed() Returns a reversed iterator
round() Rounds a numbers
set() Returns a new set object
setattr() Sets an attribute (property/method) of an object
slice() Returns a slice object
sorted() Returns a sorted list
staticmethod() Converts a method into a static method
str() Returns a string object
sum() Sums the items of an iterator

Common questions

Powered by AI

Python's model of 'call by object reference' implies that the semantics of argument passing ensure that functions receive references to the objects rather than copies or direct access. This means that for mutable objects, like lists or dictionaries, modifications within a function are reflected outside, leading to in-place changes . However, for immutable objects, such as tuples or strings, the behavior is akin to call-by-value, where changes do not affect the original object . This unified approach simplifies argument passing semantics but requires careful consideration of object mutability to avoid side effects, thereby impacting program design and bug tracking .

Lambda functions in Python are advantageous when a small, nameless function is needed for a short period of time and minimizing code verbosity is desired. They are particularly useful when passing functions as arguments to higher-order functions such as 'map()', 'filter()', and 'reduce()', where a complete function definition using 'def' may be unnecessarily verbose . Additionally, they offer a quick way to apply simple operations without the need to formally define a function, streamlining code in certain contexts .

The 'return' keyword in Python functions is used to send a result back to the caller and exit the function, effectively determining the output of the function . If a function is meant to produce a result, omitting 'return' means the function will return 'None' by default, which may not be the intended outcome and can lead to logical errors if specific output is expected by the caller . It is critical for functions that need to produce consumable outputs rather than performing actions or transformations in place .

'Call by object reference' in Python means that functions receive a reference to the arguments rather than the actual values, but with nuances depending on the mutability of the data types involved. When immutable objects like integers or strings are passed, changes within the function do not affect the original object (similar to call-by-value). For mutable objects such as lists, changes made within the function do affect the original object (similar to call-by-reference). For example, if a list is passed to a function which appends an element, the original list outside the function reflects this change, whereas changing an integer would not affect the original value outside the function scope .

Python treats functions as first-class citizens, meaning functions can be assigned to variables, stored in data structures, or passed as arguments to other functions. This enhances Python’s flexibility by allowing functions to be used in dynamic and context-sensitive ways, enabling techniques like functional programming, decorators, and callbacks . It allows for elegant code patterns such as higher-order functions and enhances capability through abstraction, leading to cleaner, more readable, and more maintainable code .

Lambda functions are particularly effective in data processing tasks by providing concise syntax that aligns well with functions like 'map()' and 'filter()'. 'Map()' applies a lambda function to all items in a list, transforming each element efficiently with minimal code, while 'filter()' uses lambda functions to screen elements, maintaining only those that satisfy the given condition, such as filtering even numbers from a list . These capabilities demonstrate lambda functions’ utility in achieving functional programming styles in Python, allowing for streamlined, readable, and efficient data transformations .

User-defined functions offer several advantages in Python, including decomposing a large program into smaller segments for better understanding and maintenance, reducing code duplication, and improving clarity. Programmers can divide work among themselves by creating functions for specific tasks . Unlike built-in or library functions, user-defined functions offer more flexibility because they can be tailored to the specific needs of the application. However, built-in functions provide convenience as they are pre-optimized and require less code to implement standard functionality .

A function definition in Python consists of several key components: the 'def' keyword which marks the start of the function, a function name that uniquely identifies the function, optional parameters for passing values, a colon to end the function header, an optional docstring to describe the function, the function body containing indented statements, and an optional return statement . These components are crucial for organizing code into modular, manageable, and reusable units, reducing repetition and improving readability and maintainability .

Lambda functions differ from regular functions in Python in that they are anonymous, consisting of a single line of code with no name, using the 'lambda' keyword instead of 'def'. They are limited to a single expression, making them less suited for longer or more complex logic . These differences mean that lambda functions are ideal for short, transient operations, especially as arguments in functions like 'map()' and 'filter()', but less suitable for tasks requiring more complex logic or debugging since they lack a name and comprehensive documentation .

Recursion in Python is a method of solving problems where a function calls itself as part of its processing. An example of a recursive function is calculating the factorial of a number, where the function multiplies the number by the factorial of the number minus one until it reaches 1 . This approach can be useful in scenarios like navigating hierarchical data structures or solving problems that can be simplified into smaller sub-problems, such as sorting algorithms or calculating Fibonacci sequences .

You might also like