0% found this document useful (0 votes)
8 views

11 Python Functions

This document provides an overview of Python functions, including their definition, types, and how to call them. It covers built-in, user-defined, and functions from modules, as well as various types of function arguments such as positional, keyword, and arbitrary arguments. Additionally, it explains the return value of functions and the concepts of pass by value and pass by reference in Python.

Uploaded by

rushikeshkonde1
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

11 Python Functions

This document provides an overview of Python functions, including their definition, types, and how to call them. It covers built-in, user-defined, and functions from modules, as well as various types of function arguments such as positional, keyword, and arbitrary arguments. Additionally, it explains the return value of functions and the concepts of pass by value and pass by reference in Python.

Uploaded by

rushikeshkonde1
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

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.

Types of Python Functions

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.

Functions defined in built-in modules

The standard library also bundles a number of modules.

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.

These functions are called user-defined functions.


Defining a Python Function

 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.

def function_name( parameters ):

"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():

"This is docstring of greetings function"

print ("Hello World")

return

Calling a Python Function

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 ):

"This prints a passed string into this function"

print (str)

return;

# Now you can call the function

printme("I'm first call to user defined function!")

printme("Again second call to the same function")

Python Function Arguments

Function arguments are the values or variables passed into a function when it is called.

The behavior of a function often depends on the arguments passed to it.

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):

"This is docstring of greetings function"

print ("Hello {}".format(name))

return

greetings("Samay")

greetings("Pratima")

greetings("Steven")
Types of Python Function Arguments

 Positional or Required Arguments

 Keyword Arguments

 Default Arguments

 Positional-only Arguments

 Keyword-only arguments

 Arbitrary or Variable-length Arguments

Positional or Required 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.

def printme( str ):

"This prints a passed string into this function"

print (str)

return;

# Now you can call printme function

printme()

Keyword Arguments

Keyword arguments are related to the function calls.

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.

Variables in the function definition are used as keywords.

When the function is called, you can explicitly mention the name and its value.
You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

def printme( str ):

"This prints a passed string into this function"

print (str)

return;

# Now you can call printme function

printme( str = "My string")

def printinfo( name, age ):

"This prints a passed info into this function"

print ("Name: ", name)

print ("Age ", age)

return;

printinfo( age=50, name="miki" )

def my_function(child3, child2, child1):

print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

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 ):

"This prints a passed info into this function"

print ("Name: ", name)

print ("Age ", age)

return;

# Now you can call printinfo function

printinfo( age=50, name="miki" )

printinfo( name="miki" )

def showinfo( name, city = "Hyderabad" ):

"This prints a passed info into this function"

print ("Name:", name)

print ("City:", city)

return

showinfo(name = "Ansh", city = "Delhi")

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.

def posFun(x, y, /, z):

print(x + y + z)

print("Evaluating positional-only arguments: ")

posFun(33, 22, z=11)

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.

def posFun( num1, num2, num3):

print(num1 * num2 * num3)

print("Evaluating keyword-only arguments: ")

posFun(num1=6, num2=8, num3=5)


Keyword 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.

Syntax: function(param1, param2,...) Syntax: function(param1 = value1,...)

Arbitrary or Variable-length Arguments

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.

Arbitrary Arguments (*args)

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.

 An argument prefixed with a single asterisk * for arbitrary positional arguments.

 An argument prefixed with two asterisks ** for arbitrary 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)

def functionname([formal_args,] *var_args_tuple ):

"function_docstring"

function_suite

return [expression]

def printinfo( arg1, *vartuple ):

"This prints a variable passed arguments"

print ("Output is: ")

print (arg1)

for var in vartuple:

print (var)

return;

# Now you can call printinfo function

printinfo( 10 )

printinfo( 70, 60, 50 )

Required Arguments With Arbitrary Arguments


It is also possible to have a function with some required arguments before the sequence of variable
number of values.

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.

def avg(first, *rest):

second=max(rest)

return (first+second)/2

result=avg(40,30,50,25)

print (result)

Arbitrary Keyword Arguments (**kwargs)

If a variable in the argument list has two asterisks prefixed to it, the function can accept arbitrary
number of keyword arguments.

The variable becomes a dictionary of keyword:value pairs.

def addr(**kwargs):

for k,v in kwargs.items():

print ("{}:{}".format(k,v))

addr(Name="John", City="Mumbai")

print ("pass four keyword args")

addr(Name="Raam", City="Mumbai", ph_no="9123134567", PIN="400001")

def percent(math, sci, **optional):

print ("maths:", math)

print ("sci:", sci)


s=math+sci

for k,v in optional.items():

print ("{}:{}".format(k,v))

s=s+v

return s/(len(optional)+2)

result=percent(math=80, sci=75, Eng=70, Hist=65, Geo=72)

print ("percentage:", result)

Order of Python Function Arguments

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.

 Then there may be one or more args with default values.

 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)

print ("a = {} b = {} a+b = {}".format(a, b, result))

Pass by Reference vs Value

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):

print ("ID inside the function:", id(arg))

var = "Hello"

print ("ID before passing:", id(var))

testfunction(var)

You might also like