My Blog
Articles related to programming, computer science, technology and research.

19/04/2018 Categories: Python Programming. No Comments on Functions in Python Programming

Contents1 Introduction to Functions2 Need for Functions3 Defining Functions4 Calling a Function5 Functions Returning Value6 Passing Arguments7 Default Arguments8 Keyword Arguments9 Variable-length Arguments10 Scope of Variables10.1 Global Statement11 Anonymous Functions or LAMBDA Functions12 Recursive Functions Introduction to Functions   A function is a block of organized and reusable program code that performs a specific, single, […]

Introduction to Functions

 

A function is a block of organized and reusable program code that performs a specific, single, and well-defined task. A function provides an interface for communication in terms of how information is transferred to it and how results are generated.

 

Need for Functions

 

  • Simplifies program development by making it easy to test separate functions.
  • Understanding programs becomes easier.
  • Libraries contain several functions which can be used in our programs to increase the productivity.
  • By dividing a large program into smaller functions, different programmers can work on different functions.
  • Users can create their own functions and use them in various locations in the main program.

 

Defining Functions

 

A function definition consists of a function header that identifies the function, followed by the body of the function. The body of a function contains the code that is to be executed when a function is called. To define a function, we have to remember following points:

 

  • Function definition starts with the keyword def
  • The keyword def is followed by the function name and parentheses.
  • After parentheses, a colon (:) should be placed.
  • Parameters or arguments that the function accepts should be placed inside the parentheses.
  • A function might have a return statement.
  • The function code should indented properly.

 

A function definition contains two parts:

 

  • Function header
  • Function body

 

The syntax of a function definition is as follows:

 

 

Example for defining a function without arguments is as follows:

 

 

In the above function definition, printstars is the function name. It prints 100 stars in the same line.

 

Example for defining a function with arguments is as follows:

 

 

Above function prints n number of stars when called. In Python, a function can be defined multiple times.

Calling a Function

 

Before calling a function, it should be defined. We call a function to execute the code inside the function. Syntax for a function call is as follows:

 

 

The arguments or parameters passed in a function call are called actual parameters. The arguments used in the function header of a function definition are called formal parameters. When a function is called, control moves to the first line inside the function definition. After the body of function definition is executed, control returns back to the next statement after the function call. Points to remember while calling a function:

 

  • The function name and number of parameters must be same in the function call and function definition.
  • When the number parameters passed doesn’t match with the parameters in the function definition, error is generated.
  • Names of arguments in the function call and function definition can be different.
  • Arguments can be passed as expressions. The expression will get executed first and then the value is passed to the formal parameter.
  • The parameter list must be separated by commas.
  • If the function returns a value it must be assigned to some variable in the calling function.

 

Let’s consider the following example which demonstrates function definition and function call:

 

 

In the above example, a and b are actual parameters, while x and y are formal parameters.

Functions Returning Value

 

A function may or may not return a value. To return a value, we must use return statement in the function definition. Every function by default contains an implicit return statement as the last line which returns None object to the calling function. A return statement is used for two reasons:

Return a value to the caller.

To end the execution of a function and give control to caller.

The syntax of return statement is as follows:

 

 

Example of a function returning a value is as follows:

 

 

In the above example, the function cube is returning the cube of value passed to it from caller.

 

Passing Arguments

 

If a function definition contains arguments, then in a function call there is a need to pass arguments. For example, in the previous function definition of cube, there is a single argument. So, while calling this function we need to pass a single parameter. The cube function can be called as follows:

 

 

In the above function call, 10 is the actual parameter.

 

Default Arguments

 

The formal parameters in a function definition can be assigned a default value. Such parameters to which default values are assigned are called default arguments. Default arguments allows a function call to pass less parameters than the number of parameters in the function definition.

 

Default value can be assigned to a parameter by using the assignment ( = ) operator. A function definition can have one or more default arguments. All the default arguments should be at the end of the arguments list. Following example demonstrates a function with default arguments and its usage:

 

 

In the example program, si(p,n) call takes the default value of 1 for r. For si(p,n,5) call, it takes the value 5 for r.

 

Keyword Arguments

 

In general, when parameters are passed in a function call, they are assigned to formal parameters based on their position. Such parameters are called positional parameters. We can also pass the parameters based on the name (keyword) of the parameter in the function definition. Such parameters are called keyword arguments.

 

In the case of keyword arguments, the actual parameters are assigned to formal parameters based on their name. Keyword arguments can be used if you don’t want to pass the parameters based on position of formal parameters. Points to remember when using keyword arguments:

 

  • All keyword parameters must match one of the parameters in the function definition.
  • Order of keyword arguments is not important.
  • A value should not be passed more than once to a keyword parameter.

 

Following example demonstrates keyword arguments and their use:

 

 

In the above example, we can see in the function call that we are passing using names (keywords) of formal parameters.

 

Variable-length Arguments

 

In some cases we cannot exactly tell how many parameters are needed in a function definition. In such cases we can use variable length arguments. Variable length arguments allows to pass random number of arguments in a function call. While creating a variable-length argument, the argument name must be preceded with * symbol. Points to remember when working with variable-length arguments:

 

  • The random arguments passed to the function forms a tuple.
  • A for loop can be used to iterate over and access the elements in the variable-length argument.
  • A variable-length argument should be at the end of the parameters list in the function definition.
  • Other formal parameters written after variable-length argument must be keyword arguments only.

 

Following example demonstrates variable-length argument:

 

 

Output of the above example is as follows:

 

 

Scope of Variables

 

Variables in a program has two things:

 

  • Scope: Parts of the program in which it is accessible.
  • Lifetime: How long a variable stays in the memory.

 

Based on scope of a variable, there are two types of variables:

 

  1. Global variables
  2. Local variables

 

Following are the differences between a global variable and local variable:

 

Global Variable Local Variable
Variable which is defined in the main body of the program file. Variable which is defined inside a function.
Accessible throughout the program file. Accessible from the point it is defined to the end of the block it is defined in.
Accessible to all functions in the program. They are not related in any way to other variables outside the function.

 

 

Following example demonstrates local and global variables:

 

 

Global Statement

 

A local variable inside a function can be made global by using the global keyword. If a local variable which is made global using the global statement have the same name as another global variable, then changes on the variable will be reflected everywhere in the program.

 

Syntax of global statement is as follows:

 

 

Following example demonstrates global keyword:

 

 

In case of nested functions:

 

  • Inner function can access variables n both outer and inner functions.
  • Outer function can access variables defined only in the outer function.

 

Anonymous Functions or LAMBDA Functions

 

Functions that don’t have any name are known as lambda or anonymous functions. Lambda functions are created using the keyword lambda. Lambda functions are one line functions that can be created and used anywhere a function is required. Lambda is simply the name of letter ‘L’ in the Greek alphabet. A lambda function returns a function object.

 

A lambda function can be created as follows:

 

 

The arguments-list contains comma separated list of arguments. Expression is an arithmetic expression that uses the arguments in the arguments-list. A lambda function can be assigned to a variable to give it a name.

Following is an example for creating lambda function and using it:

 

 

In the above example the lambda function is assigned to power variable. We can call the lambda function by writing power(3), where 3 is the argument that goes in to formal parameter x. Points to remember when creating lambda functions:

 

  • Lambda functions doesn’t have any name.
  • Lambda functions can take multiple arguments.
  • Lambda functions can returns only one value, the value of expression.
  • Lambda function does not have any return statement.
  • Lambda functions are one line functions.
  • Lambda functions are not equivalent to inline functions in C and C++.
  • They cannot access variables other than those in the arguments.
  • Lambda functions cannot even access global variables.
  • Lambda functions can be passed as arguments in other functions.
  • Lambda functions can be used in the body of regular functions.
  • Lambda functions can be used without assigning it to a variable.
  • We can pass lambda arguments to a function.
  • We can create a lambda function without any arguments.
  • We can nest lambda functions.
  • Time taken by lambda function to execute is almost similar to regular functions.

 

Recursive Functions

 

Recursion is another way to repeat code in our programs. A recursive functions is a function which calls itself. A recursive functions should contain two major parts:

 

  • base condition part: A condition which terminates recursion and returns the result.
  • recursive part: Code which calls the function itself with reduced data or information.

 

Recursion uses divide and conquer strategy to solve problems. Following is an example for recursive function which calculates factorial of a number:

 

 

In the above example test inside triple quotes is called docstring or documentation string. The docstring of function can be printed by writing function_name.__doc__

 

Following is an example for recursive function which calculates GCD of two numbers:

 

 

Related Links:

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll Up