3. Python - Functions
• A function is a block of organized, reusable code that is used to
perform a single, related action. Functions provides better modularity
for your application and a high degree of code reusing.
• As you already know, Python gives you many built-in functions like
print() etc. but you can also create your own functions. These functions
are called user-defined functions.
4. Defining a Function
Here are simple rules to define a function in Python:
• 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.
• Syntax:
• def functionname( parameters ):
• "function_docstring" function_suite return [expression]
5. • Syntax:
def functionname( parameters ):
"function_docstring”
function_code
return [expression]
By default, parameters have a positional behavior, and you need
to inform them in the same order that they were defined.
• Example:
def printme( str ):
“creating first function”
print("This prints a passed string function“)
print (str)
Printme(“Happy Programming!”)
6. Calling a Function without argument
• Following is the example to call printme() function:
def print():
“creating second function to display msg”
print(“Hello world”);
print()
print();
• This would produce following result:
Hello world
Hello world
Here function print() is called without arguments .
This function is called twice so displays Hello world
twice.
7. Calling a Function with argument i.e
Pass by reference
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:
Program to add two numbers using function with arguments
def add(a,b):
sum=a+b
print sum
add(2,3) # calling add with two arguments 2,3 will print 5
add(4,5) # calling add with two arguments 4,5 will print 9
8. Calling a Function with argument
Program to swap two numbers using function with arguments
def swap(a,b):
temp=a
a=b
b=temp
x=2
y=3
print(“before swap x=“,x,”y=“,y)
swap(x,y) # swaping two numbers using pass byreference
print(“after swap x=“,x,”y=“,y)
====Output=====
before swap x=2 y=3
after swap x=3 y=2
9. Passing List to function
def changeme( mylist ):
#This function changes a passed list
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
• So this would produce following result:
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
10. There is one more example where argument is being passed by reference but
inside the function, but the reference is being over-written.
def changeme( mylist ): "This changes a passed list"
mylist = [1,2,3,4];
print "Values inside the function: ", mylist
return
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
• The parameter mylist is local to the function changeme. Changing mylist
within the function does not affect mylist. The function accomplishes
nothing and finally this would produce following result:
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
11. Function returning value
A return statement is used to end the execution of the function
call and “returns” the result (value of the expression following
the return keyword) to the caller.
The statements after the return statements are not executed. If
the return statement is without any expression, then the special
value None is returned.
A return statement is overall used to invoke a function so that
the passed statements can be executed.
Note: Return statement can not be used outside the function.
Syntax:
def functionname(parameters):
statements
.
.
return [expression]
12. Function returning value Example
Function to find cube of a number and return value of
cube
def cube(x):
r=x**3
return r
val=cube(3)
#calls function and pass 3
#function returns value and store in val
print(“cube is”,value)
Output
Cube is 27
13. Function returning value Example
Program to find factorial of a number using function
returning value
def factorial(x):
fact=1
for i in range(1,x+1):
fact=fact*I
return fact
num=4
f=factorial(num)
print(“factorial of”,num,” is”,f)
14. Function returning Multiple values
In Python, we can return multiple values from a function
def getdata():
name = “Rahi"
rollno= 20
return rollno,name;
# call function
n,r = getdata()
print(“name=“,n)
print(“rollno=“,r)
15. Function Arguments:
A function by using the following types of formal arguments::
– Positional arguments
– Keyword arguments
– Default arguments
– Variable-length arguments
Positional arguments:
– The list of variables declared in the parentheses at the time of
defining a function are the formal arguments. And, these arguments
are also known as positional arguments. A function may be defined
with any number of formal arguments.
– While calling a function −
– All the arguments are required.
– The number of actual arguments must be equal to the number of
formal arguments.
– They Pick up values in the order of definition.
16. Positional arguments Example
def add(x,y):
z = x+y
print (z)
a = 10
b = 20
add(a, b)
It will produce the following output −
x=10 y=20 x+y=30
Here, the add() function has two formal arguments, both are
numeric.
When integers 10 and 20 passed to it. The variable "a" takes 10
and "b" takes 20, in the order of declaration. The add() function
displays the addition.
17. 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.
def printinfo( name, age ):
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function by positional
arguments
printinfo ("Naveen", 29)
# by keyword arguments
printinfo(name="miki", age = 30)
printinfo(age=40,name=“Raghav”)
18. Following example gives more clear picture. Note, here order of
the parameter does not matter:
def printinfo( name, age ): "Test function"
print "Name: ", name;
print "Age ", age;
printinfo( age=40, name=“Raghav" );
• This would produce following result:
Name: Raghav Age 40
19. 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.
• Following example gives idea on default arguments, it would
print default age if it is not passed:
def printinfo( name, age = 35 ): “Test function"
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );
printinfo( name="miki" );
• This would produce following result:
Name: miki Age 50 Name: miki Age 35
20. 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.
• The general syntax for a function with non-keyword variable
arguments is this:
def functionname([formal_args,] *args_tuple ):
function_code
return [expression]
21. • An asterisk (*) is placed before the variable name that will hold
the values of all nonkeyword variable arguments. This tuple
remains empty if no additional arguments are specified during
the function call. For example:
def printinfo(*argstuple ):
print(“in function”)
for var in vartuple:
print var
printinfo();
printinfo( 70, 60, 50 );
• This would produce following result:
Output is:
In function
Output is:
In function
70
60
50
22. The Anonymous Functions:
You can use the lambda keyword to create small anonymous functions.
These functions are called anonymous because they are not declared
in the standard manner by using the def keyword.
• 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:
lambda [arg1 [,arg2,.....argn]]:expression
23. Example:
• Following is the example to show how lembda form of function
works:
sum = lambda arg1, arg2: arg1 + arg2;
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
• This would produce following result:
Value of total : 30
Value of total : 40
24. 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
• Global vs. Local variables:
• Variables that are defined inside a function body have a local scope,
and those defined outside have a global scope.
• This means that local variables can be accessed only inside the
function in which they are declared whereas global variables can be
accessed throughout the program body by all functions. When you call
a function, the variables declared inside it are brought into scope.
25. • Example:
total = 0; # This is global variable.
def sum( arg1, arg2 ): # arg1 and arg2 are local
variables
total = arg1 + arg2;
print "Inside the function local total : ", total
# Now call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
• This would produce following result:
Inside the function local total : 30
Outside the function global total : 0
Note:
1.Scope of local variables is within function
2.Scope of global variables is outside function also.
26. Questions
• Create function to find whether number is
prime or not using function with argument
• Create a function to find area of circle
• Create a function to return area and
perimeter of cube