Python Fundamentals – User Defined Functions
INTRODUCTION
A user defined function represents a function which is named and provided by user or programmer to produce the desired and certain output. Figure 14.1 illustrates the sequence for the call to a function sqrt. The value of x (16.0) is the input, and the result after operation of the function sqrt() or output is the square root of 16.0, i.e. 4.
As described in previous Chapter, functions are of two types. These are:
- Built-in functions or library functions (already described in Chapter 13)
- User defined functions can be created by user.
In this Chapter, we shall learn about user defined functions.
Why do we use Function?
- The use of functions enables us to develop a program more easily.
- Functions may be executed more than once in a program. After we have written and tested a function. This saves you from typing the same code over again when you want to use it in another program.
- Functions hide unnecessary complexity from the user.
- Functions help you in organizing your program logically. Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a working whole.
- Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it.
PYTHON FUNCTIONS
Python function is the grouping of program statements into a single unit. Each Python function can be activated through the execution of a function call. Execution always begins at the first statement of the program. Statements are executed one at a time, in order, from top to bottom. Order in which statements are executed, is called the flow of execution.
So far we have only seen the functions which come with Python either in some file (module) or in interpreter itself (built in), but it is also possible for programmer to write their own function(s). These functions can then be combined to form a module which can then be used in other programs by importing them.
DEFINING A FUNCTION
You can define functions to provide the required functionality. Here are simple rules to define a function in Python:
- Function blocks begin with the keyword def followed by an identifier, i.e., nameof the function followed by parenthesized list of parameters and the colon which ends up the line. Next follows the block of statement(s) that are the part of function.
- A name used inside a function to refer to the value passed as an argument is called 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
The syntax for defining function is as follows:
def functionname( parameters ): " " " function_docstring" " " function_suite return [expression]
We create a function with a def statement. This provides the name, parameters and the suite of statements that creates the function’s result. By default, parameters have a positional behavior, and you need to inform them in the same order that they were defined. The function name is the name by which the function is known. The parameters is a list of variable names; these names are the local variables to which actual argument values will be assigned when the function is applied. The suite (which must be indented) is a block of statements that computes the value for the function.
There is a convention in Python to insert a documentation string right after the def line of the function definition. The documentation string, known as a docstring, should contain a short description of the purpose of the function and explain what the different arguments and return values are. Interactive sessions from a Python shell are also common to illustrate how the code is used. Docstrings are usually enclosed in triple double quotes “””, which allow the string to span several lines or summary section of exactly one line.
The return statement specifies the result value of the function. This value will become the result of applying the function to the argument values. This value is sometimes called the effect of the function.
Function Header
It begins with the keyword def and ends with colon (:), and contains the function identification details. The first line of a function definition is called function header.
Function Body
Consisting of sequence of indented (4 space) Python statement(s), to perform a task. The body can contain any number of statements. The body of the function gets executed only when the function is called/invoked. The first statement of the function body can optionally be a string constant, docstring, enclosed in triple quotes. It contains the essential information that someone might need about the function. The last statement of the function, i.e., return statement returns a value from the function. Return statement may contain a constant/literal, variable, expression or function, if return is used without anything, it will return None.
Example 1
Here is the simplest form of a Python function. This function takes a string as input parameter and prints it on standard screen.
def printme(str):
" " "This prints a passed string into this function" " "
print str
return
Figure 14.2 Python function
In the program given in Figure 14.2,
def printme( str ): # Line 1
The first line of function definition, i.e., Line 1 is called header and the rest, of the lines in our example, is known as body.
Calling/Invoking a 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 execute it by calling it from another function or directly from the Python prompt. Following is the example to call printme() function.
Example 2
#Function definition def printme( str ): # Function definition """This prints a passed string into this function""" print str return #Now you can call printme function printme("Call to user defined function") # Function calling /invoking RUN Call to user defined function
Figure 14.3 Function Definition
STRUCTURE OF A PYTHON PROGRAM
In Python, all function definitions are given at the top followed by statements also called top level statement. Internally Python gives a special name to top level statements as _main_. Python begins execution of a program from top level statements, i.e., from _main_. def statements are also read but ignored until called. The top level statements are not indented at all. In the following example line 5, 6, 7 and 8 are called top level statements. Lets study the program given in Example 3 to see how statements are executed one at a time.
- Python starts execution from the first statement, i.e., line 1. Since it is comment line so ignored by the browser.
- def statement is also read but ignored until called. So, in line 2, Python just executes the function header line to determine that it is proper function header and entire function body, i.e., line 3 and line 4 are not executed by Python.
- So actual program execution begins with first statement of _main_ segment,, i.e., line 5 and it will print testing…on console.
- Next line 6 will be executed which is again a print statement so, it will print passing the value 2 on the console.
- Statement 7, i.e., z = f(2) is a function call statement. Whenever a function call statement is encountered, function call will send the control flow to the function definition, i.e., line 2 and the value from _main_ i.e 2 is passed to it. Now the function f(x) receives the value 2 in variable x.
- Now the statements (line 3 and line 4) in the function body are executed and with the return statement or the last statement of function body, the control returns to the statement where from the function was called. Since the last statement of function body is return statement returning a value of y, i.e., 4, which will be given back to _main_ .’Now the value returned will be stored in the variable z.
- Now the statement in line 8 which is the print statement will be executed and it will display the result:
the function returns 4
Example 3
# Program for exponentiation (power) calculation #line 1 def f(x): #line 2 y = x**x # line 3 return y # line 4 print "testing..." #line 5 print "passing the value 2" #line 6 z = f(2) #line7 print "the function returns", z #line 8 RUN ››› testing... passing the value 2 the function returns 4 ›››
Figure 14.4 Program to perform exponentiation (power) calculation
Let’s consider another example. Assume you want to calculate powers, just like the built-in function pow, or the operator **. You can define the (integer) power of a number in several different ways, but let’s start with a simple one: power(x,n) (x to the power of n) is the number x multiplied by itself n-1 times (so that x is used as a factor n times). So power(2,3) is 2 multiplied with itself twice, or 2x2x2 = 8.
Example 4
def power(x, n): result = 1 for i in range(n): result *= x return result a = input("Enter number ") b = input("Raise to power ") pw = power(a, b) print a, "raise to power", b, "is", pw RUN ››› Enter number 2 Raise to power 3 2 raise to power 3 is 8 ››› =============== RESTART ============= ››› Enter number 3 Raise to power 4 3 raise to power 4 is 81 ›››
Figure 14.5 Program for power calculation
Parameters are the value(s) provided in the parenthesis when we write function header. Arguments are the value(s) provided in function call/invoke statement. The variables you write after your function name in def statements are often called the formal parameters of the function. The values you supply when you call the function are called the actual parameters, or arguments. List of arguments should be supplied in same way as parameters are listed. Bounding of parameters to arguments is done T:l, and so there should be same number and type of arguments as mentioned in parameter list.
It is common to say that the function takes arguments and return the result.
Parameters are placeholders for information that you give to a function so it can earnout an action. For example, if a function is defined as follows:
def display(message):
then, message is a parameter or formal argument. Although display has only one parameter, function can have many. To define function with multiple parameter, list them out, separated by commas.
In the following statement, It will display message for you is an argument or actual argument.
display("It will display message for you")
Here are a few things to know about function parameters:
- A function can have any number of parameters (or no parameters).
- When you define a function, you specify how many parameters it has.
- You can define default values for any or all of the parameters.
Here are a few things to know about arguments:
- Arguments are passed when you call the function.
- If the parameter has a default value, you don’t have to pass an argument.
- You can pass an argument as a literal or as a name.
In the Example 4 shown above i.e. def power(x, n):
x and n are known as parameters or formal parameters.
Where as in pw power(a, b)
a and b are known as arguments or actual arguments.
Arguments in Python can be literals, variables or expressions.
TYPES OF PARAMETERS OR FORMAL ARGUMENTS
You can call a function by using the following types of formal arguments:
- Required arguments
- Keyword arguments
- Default arguments
- Variable-length 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.
To call the function printme() you definitely need to pass one argument otherwise it would give a syntax error. See Example 5.
Example 5
# Function definition is here def printme(str): "This prints a passed string into this function" print str return # Now you can call printme function printme("This function will print passed function") RUN This function will print passed function
Figure 14.6 Demo of required arguments
When you do not pass argument to function call, i.e., you write printme() function without argument then, it will give syntax error:
Traceback (most recent call last): File "test.py", line 11, in <module> printme(); TypeError: printme() takes exactly 1 argument (0 given)
Using Positional Parameters and Positional Arguments
If you just list out a series of variable names in a function’s header, you create positional parameter.
def birthdayl(name, age):
If you call a function with just a series of values, you create positional parameter:
birthdayl ("Sai",7)
Using positional parameters and positional arguments means that parameters get their value based solely on the position of the values sent. The first parameter gets the first value sent, the second parameter gets the second value sent and so on. With this particular function call it means name gets “Sai” and age gets 7.
If you switch the positions of two arguments, the parameters get different values. So with the call
birthdayl(7, "Sai")
i.e., name gets the first value 7 and age gets the second value “Sai” which is wrong. Thus the values of arguments must match with parameters, position-wise (Positional) and order-wise. And the arguments must be provided for all parameters (Required).
Keyword Arguments
Keyword arguments are the named arguments with assigned values being passed in the function call statement, i.e., 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. You can also make keyword calls to the printme() function in the following ways:
Example 6
# Function definition def printme(str): "This prints a passed string into this function" print str return # Now you can call printme function printme(str = "My string") RUN My string
Figure 14.7 Demo of keyword arguments
When the above code is executed, it produces following result:
My string
Example 7 gives more clear picture. Note, here order of the parameter does not matter:
Example 7
# Function definition def printinfo(name, age ): "This prints a passed info into this function" print "Name: ", name print "Age: ", age return # Now you can call printinfo function printinfo(age=17, name="Vivek") RUN Name: Vivek Age: 17
Figure 14.8 Demo of keyword argument
Using Keyword(named) Arguments
You can tell the function to assign certain values to specific parameters, regardless of order, if you use keyword arguments. With keyword argument, you use the actual parameter names from the function header to link a value to a parameter. So by calling the same function birthdatl() with
birthday1(name="Sai", age=7)
name gets “Sai” and age gets 7. The importance of keyword argument is that their order doesn’t matter. It’s the keywords that link values to parameter. So, the call
birthdayl(age=7, name="Sai")
will produce the same result as above, i.e., name gets “Sai” and age gets 7, even though the values are listed in opposite order.
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.
Example 8
# Function definition def printinfo(name, age=19): "This prints a passed info into this function" print "Name: ", name print "Age: ", age return # Now you can call printinfo function printinfo(age=17, name="Vivek" ) printinfo(name="Vivek" ) RUN Name: Vivek Age: 17 Name: Vivek Age: 19
Figure 14.9 Demo of Default argument
Using Default Parameter Values
A parameter having default value in the function header is known as a default parameter. In case the user does not want to provide values (argument) at the time of calling, we can provide default argument values. Following is an example of function header with default values:
def birthday2(name= "Raj", age=5):
This means that if no value is supplied to name, it gets “Raj”. And if no value is supplied for age, it gets 5. So the call
birthday2()
will not generate an error, instead the default values are assigned to the parameters.
You can override the default values of any or all the parameter. With the call:
birthday2(name="Dev")
The default value of name is overridden, name gets “Dev”, age still gets the value 5.
Using Multiple Argument Types Together
Python allows you to combine multiple argument types in a function call. You can combine keyword argument and positional argument in a single function. But while using keyword arguments, following should be kept in mind:
- An argument list must first contain positional arguments followed by any keywords arguments.
- Keywords in argument list should be from the list of parameters name only.
- You cannot specify a value for an argument more than once.
- Parameter names corresponding to positional arguments cannot be used as keywords in the same calls.
Some function arguments can be given a default value so that we may leave out these argument’s in the call, if desired. A typical function may look as:
››› def somefunc(argl, arg2, kwargl=4, kwarg2=8): ››› print argl, arg2, kwargl, kwarg2
The first two arguments, argl and arg2, are ordinary or positional arguments, while the latter two are keyword arguments or named arguments. Each keyword argument has a name (in this example kwargl and kwarg2) and an associated default value. The keyword arguments must always be listed after the positional arguments in the function definition.
When calling somefunc(), we may leave out some or all of the keyword arguments. Keyword arguments that do not appear in the call get their values from the specified default values. We can demonstrate the effect through some calls has summarized in Table 14.1.
Table 14.1 somefunc() legal function calls
Function Call Statement | Legal/illegal | Result |
somefunc(3,2) | Legal | 3 24 8 |
somefunc(10,20,30,40) | Legal | 10 20 30 40 |
somefunc(25,50,kwarg2=100) | Legal | 25 50 4 100 |
somefunc(kwarg2=2,argl=3,arg2=4) | Legal | 3 4 4 2 |
Notice that 1st and 2nd call to function is based on default argument value, and the 3rd and 4th call are using keyword arguments.
In the first usage, values 3 and 2 are passed on to argl and arg2, respectively. Thus they all work with default values.
In second call, all the four parameters get values in function call statement.
In third usage, variable argl gets the first value 25, arg2 gets the value 50 due to the position of the argument. And parameter kwarg2 gets the value 100 due to naming, i.e., keyword arguments. The parameter kwargl uses the default value, i.e., 4.
In the fourth usage, we use keyword argument for all specified value. Keyword arguments can be used in any order and for argument skipped, there is a default value. Table 14.2 illustrates some illegal function calls.
Table 14.2 somefunc() illegal function calls
Function call statement | Legal/illegal | Result |
somefunc() | illegal | Required or positional argument missing, i.e., somefunc() takes at least 2 arguments (0 given) |
somefunc(kwarg1=10, kwarg2=20 ,30,40) |
illegal | Keyword arguments are placed before positional arguments. |
somefunc(4,5,arg2=6) | illegal | somefunc() got multiple values for keyword argument ‘arg2’ |
somefunc(4,5,kwargl=5, kwarg3= 6) ‘ ‘ |
illegal | Undefined name kwarg3 used. |
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 as follows:
def functionname([formal args, ] *var_args_tuple): "function_docstring" function_suite return [expression]
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. Following is a simple example.
Example 9
# Function definition 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 )
Figure 14.10 Demo of variable length arguments
When the above code is executed, it produces following result:
Output is:
10
Output is:
70
60
50
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 dambda 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
Following is the example to show how lambda form of function works:
Example 10
# Function definition sum = lambda arg1, arg2: arg1+ arg2; # Now you can call sum as a function print "Value of total : ", sum( 10, 20 ) print "Value of total : ", sum( 20, 20 ) RUN ››› Value of total : 30 Value of total : 40 ›››
Figure 14.11 Demo of Anonymous function
return STATEMENT
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.
All the above examples are not returning any value, but if you like you can return a value from a function as shown in Example 11.
Example 11
# Function definition def sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2 print "Inside the function : ", total return total # Now you can call sum function total = sum( 10, 20 ) print "Outside the function : ", total RUN Inside the function : 30 Outside the function : 30
Figure 14.12 Demo of return statement
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
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. Let us discuss about global scope of a variable in brief. Here is a summary about global variables.
- The global names are variables assigned at the top level of the enclosing module file.
- The global names must be declared only if they are assigned within a function.
- Global variables must be referenced within a function without being declared. See Example 12.
Example 12
total = 0; # This is global variable. # Function definition def sum( arg1, arg2 ) : # Add both the parameters and return them." total = arg1 + arg2; # Here total is local variable, print "Inside the function local total : ", total return total # Now you can call sum function sum( 10, 20 ) print "Outside the function global total : ", total
Figure 14.13 Demo of local and global variable
When the above code is executed, it produces following result:
Inside the function local total: 30
Outside the function global total: 0
void FUNCTION
A function that doesn’t return a value is called void function or non-fruitful function whereas a function that returns a value is called fruitful function.
void functions might display something on the screen or have some other effect, but they don’t have a return value. If you try to assign the- result to a variable, you get a special value called None.
››› result = print_twice('Big') Big Big ››› print result None
The value None is not the same as the string ‘None’. It is a special value that has its own type:
››› print type(None) ‹type 'NoneType'›
SOLVED EXERCISE
Question 1.
Define function.
Answer:
Python function is the grouping of program statements into a single unit. Each Python function can be activated through the execution of a function call.
Question 2.
What do you mean by flow of execution?
Answer:
Execution always begins at the first statement of the program. Statements are executed one at a time, in order, from top to bottom. Order in which statements are executed, is called the flow of execution.
Question 3.
What is the function of keyword void in function declaration?
Answer:
void may be used to declare functions that do not return a value. Thus, functions with no return value will have a new type: void.
Question 4.
What is function header?
Answer:
The first line of a function definition is called function header. It begins with the keyword def and ends with colon (:) and contains the function identification details.
Question 5.
What is function body?
Answer:
The sequence of statements inside a function definition is called function body. The body of the function gets executed only when the function is called/invoked.
Question 6.
What is the significance of top level statement?
Answer:
In Python all function definitions are given at the top followed by statements also called top level statement. Internally Python gives a special name to top level state-ments as _main_. Python begins execution of a program from top level statements, i.e., from _main_. def statements are also read but ignored until called. The top level statements are not indented at all.
Question 7.
What do you mean by parameter and argument?
Answer:
Parameters are the value(s) provided in the parenthesis when we write function header. Arguments are the value(s) provided in function call/invoke statement.
Question 8.
Differentiate between required argument and default argument.
Answer:
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.
A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument.
Question 9.
Write a short note on keyword argument.
Answer:
Keyword arguments are the named arguments with assigned values being passed in the function call statement, i.e., when you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.
Question 10.
What do you mean by anonymous function?
Answer:
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.
Question 11.
What do you mean by parameter?
Answer:
A name used inside a function to refer to the value passed as an argument is called parameter. Any input parameters or arguments should be placed within these paren-theses.
Question 12.
Write a program to print Fibonacci series.
Answer:
Fibonacci series def fib(n): """Print a Fibonacci series up to n.""" a, b = 0, 1 while (a ‹ n): print a, a, b = b, a+b # Now call the function we just defined: fib(200) RUN ››› 0 1 1 2 3 5 8 13 21 34 55 89 144 ›››
Figure 1 Program for Q12
Question 13.
Write a function to calculate factorial of entered number.
Answer:
# Factorial calculation def fact(n): " " "Function to calculate factorial" " " result = n for i in range(1,n): result *= i return result number = input("Enter number : ") factorial = fact(number) print "Factorial of number ", number, "is ", factorial RUN ››› Enter number : 5 Factorial of number 5 is 120 ›››
Figure 2 Program for Q13
Question 14.
Write a function to check entered number is even or odd.
Answer:
# Function to check entered number is even or odd def check(num): if (num%2==0): print "Number is even" else: print "number is odd" number = int(raw_input("Enter a number: ")) result = check(number) RUN ››› Enter a number: 5 number is odd ››› =============== RESTART ============= ››› Enter a number: 4 Number is even ›››
Figure 3 Program for Q14
Question 15.
Differentiate between local and global variables.
Answer:
A local variable is one that is defined within a function. The scope of a local variable is limited to the function in which it is defined. The life of local variable is limited to the function. Global variable are defined outside the main function block. The scope of global variable is throughout the program. The life of global variable is throughout the program.
Question 16. Multiple choice questions
Question 1.
Which of the following is not a legal return statement?
- return 6
- return 5+8
- return 3**3
- All are legal
Answer:
All are legal
Question 2.
The value being returned can be:
- A literal
- A variable
- An expression
- All of the above
Answer:
All of the above
Question 3.
Function not returning any value is called:
- non-void
- illegal
- void
- None of the above
Answer:
void
Question 4.
No value can be skipped from the function call or you cannot change the order is called:
- Positional arguments
- Required arguments
- Mandatory argument
- All of the above
Answer:
All of the above
Question 5.
The alternative name for argument is:
- Actual parameter
- Formal parameter
- Formal argument
- None of the above
Answer:
Actual parameter