Python Fundamentals – User Defined Functions

Python Fundamentals – User Defined Functions

INTRODUCTION

A user defined function represents a func­tion 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 out­put is the square root of 16.0, i.e. 4.
python-fundamentals-user-defined-functions-fig14.1
As described in previous Chapter, func­tions 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 writ­ten 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 pro­gram 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 documenta­tion 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:

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 posi­tional 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 con­tain 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 identi­fication 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.

Figure 14.2 Python function

In the program given in Figure 14.2,

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

 

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 pass­ing 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

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

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 parame­ters 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 earn­out an action. For example, if a function is defined as follows:

then, message is a parameter or formal argument. Although display has only one param­eter, 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 argu­ment.

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 func­tion 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

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:

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.

If you call a function with just a series of values, you create positional parameter:

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 partic­ular 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

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 inter­preter 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

Figure 14.7 Demo of keyword arguments

When the above code is executed, it produces following result:

Example 7 gives more clear picture. Note, here order of the parameter does not matter:

Example 7

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

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

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 pro­vided 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

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 parame­ter. 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:

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

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:

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 key­words 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 key­words 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:

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 key­word 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 StatementLegal/illegalResult
somefunc(3,2)Legal3 24 8
somefunc(10,20,30,40)Legal10 20 30 40
somefunc(25,50,kwarg2=100)Legal25 50 4 100
somefunc(kwarg2=2,argl=3,arg2=4)Legal3 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 argu­ments 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 statementLegal/illegalResult
somefunc()illegalRequired or positional argument missing, i.e., somefunc() takes at least 2 arguments (0 given)
somefunc(kwarg1=10,
kwarg2=20 ,30,40)
illegalKeyword arguments are placed before positional arguments.
somefunc(4,5,arg2=6)illegalsomefunc() got multiple values for keyword argu­ment ‘arg2’
somefunc(4,5,kwargl=5,
kwarg3= 6) ‘ ‘
illegalUndefined name kwarg3 used.

Variable-Length Arguments
You may need to process a function for more arguments than you specified while defin­ing 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:

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

Example 9

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:

Following is the example to show how lambda form of function works:

Example 10

Figure 14.11 Demo of Anonymous function

return STATEMENT
The statement return [expression] exits a function, optionally passing back an expres­sion 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

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

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.

The value None is not the same as the string ‘None’. It is a special value that has its own type:

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 func-tions 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:

Figure 1 Program for Q12

Question 13.
Write a function to calculate factorial of entered number.

Answer:

Figure 2 Program for Q13

Question 14.
Write a function to check entered number is even or odd.

Answer:

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

About the author

James Palmer

Leave a Comment