Skip to content

Functions in Python

wilsonshamim edited this page Jun 12, 2018 · 4 revisions

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

to create a function:

Syntax
def functionname( parameters ):
“function_docstring”
function_suite
return [expression]

example:

def sum(a,b):
sum = a+b
return sum

print(“doing sum…”)
s = sum(23,4)
print(“sum is :”, s)

Pass by reference vs value
All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example −

#!/usr/bin/python

  1. Function definition is here
    def changeme( mylist ):
    “This changes a passed list into this function”
    mylist.append([1,2,3,4]);
    print "Values inside the function: ", mylist
    return
  1. Now you can call changeme function
    mylist = [10,20,30];
    changeme( mylist );
    print "Values outside the function: ", mylist

o/P :
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

Function Arguments
You can call a function by using the following types of formal arguments −

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.

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.

e.g:
def changelist(lis,str,in1):
lis.append([1,2,3])
print(lis)
print(str)
print(in1)

lis = [11,22,33]
changelist(lis=lis,in1 = 100,str=“shamim”)
print(lis)

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

def defau(name, age=13:
print(“name”,name)
print(“age”,age)

defau(name=232)

note: the default value should be placed at the end of the argument list.
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
Syntax for a function with non-keyword variable arguments is this −

def functionname([formal_args,] *var_args_tuple ):
“function_docstring”
function_suite
return [expression]

An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example −

def mul(arg1,*arg2):
print(“only one value supploed”, arg1)

print(“Multiple values supploed…”) for x in arg2: print(x)

mul(10)
mul(10,34,55,555,“shamim”,[2,3,4])

O/P:
only one value supploed 10
Multiple values supploed…
only one value supploed 10
Multiple values supploed…
34
55
555
shamim
[2, 3, 4]


The Anonymous Functions
These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions.

Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.

An anonymous function cannot be a direct call to print because lambda requires an expression

Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.

Although it appears that lambda’s are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons.

Syntax
The syntax of lambda functions contains only a single statement, which is as follows −

lambda [arg1 [,arg2,…..argn]]:expression

example:
l = lambda a,b,c: a+b*c

print(l(1,2,4))


  1. Function definition is here
    sum = lambda arg1, arg2: arg1 + arg2;
  1. Now you can call sum as a function
    print "Value of total : ", sum( 10, 20 )
    print "Value of total : ", sum( 20, 20 )
    When the above code is executed, it produces the following result −

Value of total : 30
Value of total : 40

Clone this wiki locally