2. Python Functions
• 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.
4. Above shown is a function definition that consists of the
following components.
• Keyword def that marks the start of the function header.
• A function name to uniquely identify the function. Function
naming follows the same rules of writing identifiers in
Python.
• Parameters (arguments) through which we pass values to
a function. They are optional.
5. • A colon (:) to mark the end of the function header.
• Optional documentation string (docstring) to describe
what the function does.
• One or more valid python statements that make up the
function body. Statements must have the same
indentation level (usually 4 spaces).
• An optional return statement to return a value from the
function.
6. Example of a function
def display(name):
"""
This function displays the name of the
person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
7. 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.
• Syntax:
>>> display('abc')
8. Note: In python, the function definition should
always be present before the function call.
Otherwise, we will get an error.
9. Docstring
• The first string after the function header is called the
docstring and is short for documentation string. It is briefly
used to explain what a function does.
• In the above example, we have a docstring immediately
below the function header. We generally use triple quotes
so that docstring can extend up to multiple lines. This
string is available to us as the __doc__ attribute of the
function.
10. The return statement
• The return statement is used to exit a function and go
back to the place from where it was called.
• Syntax of return:
return [expression_list]
11. • This statement can contain an expression that gets
evaluated and the value is returned.
• If there is no expression in the statement or the return
statement itself is not present inside a function, then the
function will return the None object.
12. Example (Return)
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num
print(absolute_value(2))
print(absolute_value(-4))
14. Parameters
• A parameter is the variable defined within the parentheses
during function definition.
• Simply they are written when we declare a function.
• Example:
# Here a,b are the parameters
def sum(a,b):
print(a+b)
sum(1,2)
15. Arguments
• An argument is a value that is passed to a function when
it is called. It might be a variable, value or object passed
to a function or method as input. They are written when
we are calling the function.
• Example:
def sum(a,b):
print(a+b)
# Here the values 1,2 are arguments
sum(1,2)
16. Note
• If any functions is having two parameters and we have
called that function with two arguments, then it will run
smoothly.
• But if a function is havinng two parameters and we are
calling that function with just one argument then it will give
error.
• Hence there shouldn’t be difference in number of
parameters and arguments while calling the function.
17. Variable Function Arguments
• Up until now, functions had a fixed number of arguments.
In Python, there are other ways to define a function that
can take variable number of arguments.
• Three different forms of this type are described below:
1. Python Default Arguments
2. Python Keyword Arguments
3. Python Arbitrary Arguments
18. Python Default Arguments
• Function arguments can have default values in Python.
• We can provide a default value to an argument by using
the assignment operator (=).
• Here is an example.
19. Example
def greet(name, msg="Good morning!"):
"""
This function greets to the person with the
provided message.
If the message is not provided,it defaults to "Goodmorning!"
"""
print("Hello", name + ', ' + msg)
greet("Kate")
greet("Bruce", "How do you do?")
20. • In this function, the parameter name does not have a default
value and is required (mandatory) during a call.
• On the other hand, the parameter msg has a default value of
"Good morning!". So, it is optional during a call. If a value is
provided, it will overwrite the default value.
• Any number of arguments in a function can have a default value.
But once we have a default argument, all the arguments to its
right must also have default values.
21. • This means to say, non-default arguments cannot follow
default arguments. For example, if we had defined the
function header above as:
def greet(msg = "Good morning!", name):
• You will get an error.
22. Python Keyword Arguments
• When we call a function with some values, these values
get assigned to the arguments according to their position.
• For example, in the above function greet(), when we
called it as greet("Bruce", "How do you do?"), the value
"Bruce" gets assigned to the argument name and similarly
"How do you do?" to msg.
23. • Python allows functions to be called using keyword arguments.
When we call functions in this way, the order (position) of the
arguments can be changed. Following calls to the above function
are all valid and produce the same result.
• # 2 keyword arguments
• greet(name = "Bruce",msg = "How do you do?")
• # 2 keyword arguments (out of order)
• greet(msg = "How do you do?",name = "Bruce")
• 1 positional, 1 keyword argument
• greet("Bruce", msg = "How do you do?")
24. • As we can see, we can mix positional arguments with keyword
arguments during a function call. But we must keep in mind that
keyword arguments must follow positional arguments.
• Having a positional argument after keyword arguments will result
in errors. For example, the function call as follows:
greet(name="Bruce","How do you do?")
25. Python Arbitrary Arguments
• Sometimes, we do not know in advance the number of
arguments that will be passed into a function. Python
allows us to handle this kind of situation through function
calls with an arbitrary number of arguments.
• In the function definition, we use an asterisk (*) before the
parameter name to denote this kind of argument.
26. Example
def greet(*names):
"""This function greets all
the person in the names tuple."""
# names is a tuple with arguments
for name in names:
print("Hello", name)
greet("Monica", "Luke", "Steve", "John")
27. • Here, we have called the function with multiple
arguments. These arguments get wrapped up into a tuple
before being passed into the function. Inside the function,
we use a for loop to retrieve all the arguments back.
28. Scope of Variables
• All variables in a program may not be accessible at all
locations in that program. This depends on where you
have declared a variable.
• The scope of a variable determines the portion of the
program where you can access a particular identifier.
There are two basic scopes of variables in Python −
• Global variables
• Local variables
29. Local Variables
• Local variables are those which are initialized inside a function
and belong only to that particular function. It cannot be accessed
anywhere outside the function. Let’s see how to create a local
variable.
• Example:
def f():
# local variable
s = "python"
print(s)
# Driver code
f()
30. • If we will try to use this local variable outside the function
then let’s see what will happen.
• Example:
def f():
# local variable
s = "python"
print("Inside Function:", s)
f()
print(s)
• An error message will be there because ‘s’ is not defined in the scope.
31. Global Variables
• These are those which are defined outside any function
and which are accessible throughout the program, i.e.,
inside and outside of every function. Let’s see how to
create a global variable.
• Example: Defining and accessing global variables
32. Example
# This function uses global variable s
def f():
print("Inside Function", s)
# Global scope
s = "python"
f()
print("Outside Function", s)
• The variable s is defined as the global variable and is used both inside the
function as well as outside the function.
33. • Note: As there are no locals, the value from the globals
will be used but make sure both the local and the global
variables should have same name.
• Now, what if there is a variable with the same name
initialized inside a function as well as globally. Let’s see
that with help of an example.
34. Example
# This function has a variable with
# name same as s.
def f():
s = "class"
print(s)
# Global scope
s = "python"
f()
print(s)
35. • If a variable with the same name is defined inside the
scope of function as well then it will print the value given
inside the function only and not the global value.
• The question is, what if we try to change the value of a
global variable inside the function. Let’s see it using the
below example.
36. Example
# This function uses global variable s
def f():
s += 'class'
print("Inside Function", s)
# Global scope
s = "python"
f()
OUTPUT:
UnboundLocalError: local variable 's' referenced before assignment
• To make the above program work, we need to use the “global” keyword.
37. • We only need to use the global keyword in a function if we want to
do assignments or change the global variable. global is not
needed for printing and accessing.
• Python “assumes” that we want a local variable due to the
assignment to s inside of f(), so the first statement throws the
error message.
• Any variable which is changed or created inside of a function is
local if it hasn’t been declared as a global variable. To tell Python,
that we want to use the global variable, we have to use the
keyword “global”, as can be seen in the upcoming example:
38. Example Using global keyword
# This function modifies the global variable 's'
def f():
global s
s += 'class'
print(s)
s = "new python"
print(s)
# Global Scope
s = "Python"
f()
print(s)
41. Anonymous/Lambda Function
• 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.
42. Syntax of lamba function
• Syntax:
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.
43. Example
# Program to show the use of lambda functions
double = lambda x: x * 2
print(double(5))
44. • 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.
45. double = lambda x: x * 2
is nearly the same as:
def double(x):
return x * 2
46. 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.
47. 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.
48. Example
# 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)
49. 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.
50. Example
# 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)
51. Function within Functions
• A function that is defined inside another function is known
as the inner function or nested function.
• Nested functions are able to access variables of the
enclosing scope.
• Inner functions are used so that they can be protected
from everything happening outside the function.
52. Example
# Python program to
# demonstrate accessing of
# variables of nested functions
def f1():
s = 'I love GeeksforGeeks'
def f2():
print(s)
f2()
# Driver's code
f1()
54. Type Conversion
• Type Conversion, just as the name suggests, is the process of
converting the type of objects from one data type into another as
per requirement.
• Python supports various built-in type conversion functions such as
int(), long(), float(), str() etc,.
• This type of conversion is also called as Explicit Type Conversion
or Type Casting.
55. • When a user will try to add a string and an integer, Since
python does not allow a string and an integer to be added,
both should be converted to the same data type.
Therefore, we explicitly convert string b to int datatype
(int(b)).
• It is worth to keep in mind that in Explicit Type
Conversion, there may be chances of data loss as we
enforce an object to a specified datatype.
56. Type Coercion
• The automatic type conversion from one data type to
another is called as Type Coercion. This is also called as
Implicit Type Conversion.
• The major difference between Type Conversion and Type
Coercion is that, type conversion is done manually using
built-in functions where as type coercion is done
automatically.
57. • For example, a is an integer and the data type of b is
float. When the two are added, we can see that the result
has a datatype of float. This is because, python always
converts smaller datatypes to larger data types in order to
avoid loss of data.
59. Recursion
• Recursion is the process of defining something in terms of
itself.
• 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.
• A function is called recursive if a statement within the
body of the function calls the same function.
62. • When we call this function with a positive integer, it will
recursively call itself by decreasing the number.
• Each function multiplies the number with the factorial of
the number below it until it is equal to one.
64. • Our recursion ends when the number reduces to 1. This is called the base
condition.
• Every recursive function must have a base condition that stops the recursion
or else the function calls itself infinitely.
• The Python interpreter limits the depths of recursion to help avoid infinite
recursions, resulting in stack overflows.
• By default, the maximum depth of recursion is 1000. If the limit is crossed, it
results in RecursionError.
66. Advantages of Recursion
• Recursive functions make the code look clean and
elegant.
• A complex task can be broken down into simpler sub-
problems using recursion.
• Sequence generation is easier with recursion than using
some nested iteration.
67. Disadvantages of Recursion
• Sometimes the logic behind recursion is hard to follow
through.
• Recursive calls are expensive (inefficient) as they take up
a lot of memory and time.
• Recursive functions are hard to debug.
68. setrecursionlimit()
• The setrecursionlimit function is used to modify the default
recursion limit set by python. Using this,we can increase
the recursion limit to satisfy our needs
• Syntax:
import sys
sys.setrecursionlimit(10**6)
69. Python Modules
• Modules refer to a file containing Python statements and
definitions.
• A file containing Python code, for example: example.py, is
called a module, and its module name would be example.
• We use modules to break down large programs into small
manageable and organized files. Furthermore, modules
provide reusability of code.
70. • We can define our most used functions in a module and
import it, instead of copying their definitions into different
programs.
• Let us create a module. Type the following and save it as
sample.py.
• Here, we have defined a function Example inside a
module named sample.
71.
72. Import modules in Python
• We can import the definitions inside a module to another
module or the interactive interpreter in Python.
• We use the import keyword to do this. To import our
previously defined module sample, we type the following
in the Python prompt.
import sample
73. • This does not import the names of the functions defined in
sample directly in the current symbol table. It only imports
the module name sample there.
• Using the module name we can access the function using
the dot . operator.
sample.example()
75. Re-naming a Module
• You can create an alias when you import a module, by
using the as keyword:
import sample as s
s.Example()
76. Advantages of modules
• Reusability: Working with modules makes the code
reusability a reality.
• Simplicity: Module focuses on a small proportion of the
problem, rather than focusing on the entire problem.
• Scoping: A separate namespace is defined by a module
that helps to avoid collisions between identifiers.
77. Python from...import statement
• We can import specific names from a module without
importing the module as a whole. Here is an example.
• Example:
from sample import location
print(location)
78. • Here, we imported only the location variable from the
sample module.
• In such cases, we don't use the dot operator. We can also
import multiple attributes as follows:
from sample import location, x