0% found this document useful (0 votes)
73 views12 pages

Function in Python

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 12

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.

1.Keyword  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.
3.Parameters (arguments) through which we pass values to a function. They are optional.

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

5.Optional documentation string (docstring) to describe what the function does.

6.One or more valid python statements that make up the function body. Statements must
have the same indentation level (usually 4 spaces).
7.An 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):
    list.append(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 strmylist.append(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

You might also like