11 Python Functions
11 Python Functions
A Python function is a block of organized, reusable code that is used to perform a single, related
action.
Functions provide better modularity for your application and a high degree of code reusing.
A top-to-down approach towards building the processing logic involves defining blocks of
independent reusable functions.
A Python function may be invoked from any other function by passing required data
(called parameters or arguments).
The called function returns its result back to the calling environment.
Built-in functions
Python's standard library includes number of built-in functions. Some of Python's built-in functions
are print(), int(), len(), sum(), etc.
These functions are always available, as they are loaded into computer's memory as soon as you
start Python interpreter.
Each module defines a group of functions. These functions are not readily available.
You need to import them into the memory from their respective modules.
User-defined functions
In addition to the built-in functions and functions in the built-in modules, you can also create your
own functions.
Function blocks begin with the keyword def followed by the function name and parentheses
().
Any input parameters or arguments should be placed within these parentheses. You can also
define parameters inside these parentheses.
The first statement of a function can be an optional statement; the documentation string of
the function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an expression to
the caller. A return statement with no arguments is the same as return None.
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the same order
that they were defined.
Once the function is defined, you can execute it by calling it from another function or directly from
the Python prompt.
def greetings():
return
Defining a function only gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code.
Once the basic structure of a function is finalized, you can call it by using the function name itself.
If the function requires any parameters, they should be passed within parentheses.
If the function doesn't require any parameters, the parentheses should be left empty.
def printme( str ):
print (str)
return;
Function arguments are the values or variables passed into a function when it is called.
While defining a function, you specify a list of variables (known as formal parameters) within the
parentheses.
These parameters act as placeholders for the data that will be passed to the function when it is
called.
When the function is called, value to each of the formal arguments must be provided. Those are
called actual arguments.
def greetings(name):
return
greetings("Samay")
greetings("Pratima")
greetings("Steven")
Types of Python Function Arguments
Keyword Arguments
Default Arguments
Positional-only Arguments
Keyword-only arguments
Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the function definition,
otherwise the code gives a syntax error.
print (str)
return;
printme()
Keyword Arguments
When you use keyword arguments in a function call, the caller identifies the arguments by the
parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is able
to use the keywords provided to match the values with parameters.
Python allows to pass function arguments in the form of keywords which are also called named
arguments.
When the function is called, you can explicitly mention the name and its value.
You can also send arguments with the key = value syntax.
print (str)
return;
return;
Default Arguments
A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument.
Python allows to define a function with default value assigned to one or more formal arguments.
Python uses the default value for such an argument if no value is passed to it.
If any value is passed, the default value is overridden with the actual value passed.
def printinfo( name, age = 35 ):
return;
printinfo( name="miki" )
return
showinfo(name = "Shrey")
Positional-only arguments
Those arguments that can only be specified by their position in the function call is called
as Positional-only arguments.
They are defined by placing a "/" in the function's parameter list after all positional-only parameters.
This feature was introduced with the release of Python 3.8.
The benefit of using this type of argument is that it ensures the functions are called with the correct
arguments in the correct order.
The positional-only arguments should be passed to a function as positional arguments, not keyword
arguments.
In the following example, we have defined two positional-only arguments namely "x" and "y". This
method should be called with positional arguments in the order in which the arguments are
declared, otherwise, we will get an error.
print(x + y + z)
Keyword-only arguments
Those arguments that must be specified by their name while calling the function is known
as Keyword-only arguments.
They are defined by placing an asterisk ("*") in the function's parameter list before any keyword-only
parameters.
This type of argument can only be passed to a function as a keyword argument, not a positional
argument.
Positional Argument
Only the names of arguments are used to pass data Keyword arguments are passed to a function in
to the given function. name=value form.
Arguments are passed in the order defined in While passing arguments, their order can be
function declaration. changed.
You may need to process a function for more arguments than you specified while defining the
function.
These arguments are called variable-length arguments and are not named in the function definition,
unlike required and default arguments.
You may want to define a function that is able to accept arbitrary or variable number of arguments.
Moreover, the arbitrary number of arguments might be positional or keyword arguments.
The args variable prefixed with "*" stores all the values passed to it. Here, args becomes a tuple. We
can run a loop over its items to add the numbers.
An asterisk (*) is placed before the variable name that holds the values of all non-keyword variable
arguments.
This tuple remains empty if no additional arguments are specified during the function call.
def add(*args):
s=0
for x in args:
s=s+x
return s
result = add(10,20,30,40)
print (result)
result = add(1,2,3)
print (result)
"function_docstring"
function_suite
return [expression]
print (arg1)
print (var)
return;
printinfo( 10 )
The following example has avg() function. Assume that a student can take any number of tests. First
test is mandatory. He can take as many tests as he likes to better his score. The function calculates
the average of marks in first test and his maximum score in the rest of tests.
The function has two arguments, first is the required argument and second to hold any number of
values.
second=max(rest)
return (first+second)/2
result=avg(40,30,50,25)
print (result)
If a variable in the argument list has two asterisks prefixed to it, the function can accept arbitrary
number of keyword arguments.
def addr(**kwargs):
print ("{}:{}".format(k,v))
addr(Name="John", City="Mumbai")
print ("{}:{}".format(k,v))
s=s+v
return s/(len(optional)+2)
A function can have arguments of any of the types defined above. However, the arguments must be
declared in the following order −
The argument list begins with the positional-only args, followed by the slash (/) symbol.
It is followed by regular positional args that may or may not be called as keyword arguments.
Next, arbitrary positional arguments represented by a variable prefixed with single asterisk,
that is treated as tuple. It is the next.
If the function has any keyword-only arguments, put an asterisk before their names start.
Some of the keyword-only arguments may have a default value.
Last in the bracket is argument with two asterisks ** to accept arbitrary number of keyword
arguments.
Python Function with Return Value
The return keyword as the last statement in function definition indicates end of function block, and
the program flow goes back to the calling function.
Although reduced indent after the last statement in the block also implies return but using explicit
return is a good practice.
Along with the flow control, the function can also return value of an expression to the calling
function.
The value of returned expression can be stored in a variable for further processing.
def add(x,y):
z=x+y
return z
a=10
b=20
result = add(a,b)
call by value − When a variable is passed to a function while calling, the value of actual arguments is
copied to the variables representing the formal arguments.
Thus, any changes in formal arguments does not get reflected in the actual argument. This way of
passing variable is known as call by value.
call by reference − In this way of passing variable, a reference to the object in memory is passed.
Both the formal arguments and the actual arguments (variables in the calling code) refer to the same
object.
Hence, any changes in formal arguments does get reflected in the actual argument.
Python uses pass by reference mechanism.
As variable in Python is a label or reference to the object in the memory, both the variables used as
actual argument as well as formal arguments really refer to the same object in the memory.
We can verify this fact by checking the id() of the passed variable before and after passing.
def testfunction(arg):
var = "Hello"
testfunction(var)