SoFunction
Updated on 2024-12-19

Detailed explanation of the use of various functions in Python

Functions are organized, reusable blocks of code used to perform a single, related action. Functions provide better modules for applications and a high degree of code reuse.

As we know, Python has many built-in functions such as print(), but it is also possible to create your own functions. These functions are called user-defined functions.
Define a function

Functions can be defined to provide the desired functionality. Here are simple rules to define Python functions.

  • Function blocks begin with the start keyword def followed by the function name and (()) in parentheses.
  • Any input parameters or arguments should be placed within these brackets. Parameters within these brackets can also be defined.
  • The first statement of a function can be ????? An optional declaration - the function or the document string of the document string.
  • Blocks of code within each function begin with a colon (:) and are indented.
  • This statement returns [expression] to exit the function, optionally passing back an expression to the caller. The return statement without arguments returns None.

Syntax.

def functionname( parameters ):
  "function_docstring"
  function_suite
  return [expression]

By default, the parameters have the behavior and need of a location, and they are defined to notify them in the same order.
Example:

This is the simplest form of Python function. This function accepts a string as an input parameter and prints the standard screen.

def printme( str ):
  "This prints a passed string into this function"
  print str
  return

call function

Defining a function gives only its name, specifying the parameters to be included in the block of code for the function and structure.

Once the basic structure of a function has been determined, you can execute it by calling it from another function or directly from the Python prompt. The following is an example call to the printme() function:

#!/usr/bin/python

# 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("I'm first call to user defined function!");
printme("Again second call to the same function");

When the above code is executed, the following result is produced:

I'm first call to user defined function!
Again second call to the same function

Reference vs. Value Passing

All parameters (arguments) are passed by reference in the Python language. This means that if you change the value of a parameter in a function, the change is also reflected in the calling function. Example:

#!/usr/bin/python

# Function definition is here
def changeme( mylist ):
  "This changes a passed list into this function"
  ([1,2,3,4]);
  print "Values inside the function: ", mylist
  return

# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

Here, we keep the reference of the passed object and attach the value to the same object. In this way, this produces the following result:

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

There's also the example of parameters being passed by reference and references being overwritten inside the function being called.

#!/usr/bin/python

# Function definition is here
def changeme( mylist ):
  "This changes a passed list into this function"
  mylist = [1,2,3,4]; # This would assig new reference in mylist
  print "Values inside the function: ", mylist
  return

# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

Arguments myList on the local function changeme. changing mylist within the function does not affect mylist. function has no effect, and finally this produces the following result:

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

function parameters:

You can call a function by using the type of the formal parameter as follows:

  • Required parameters
  • Keyword parameters
  • default parameter
  • Variable Length Parameters

Required parameters:

The required parameters are those passed to the function in the correct positional order. Here, the number of arguments in a function call should match the function definition exactly.

To call the function printme(), be sure to pass an argument, otherwise a syntax error will be given as follows:

#!/usr/bin/python

# 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();

When the above code is executed, the following result is produced:

Traceback (most recent call last):
 File "", line 11, in <module>
  printme();
TypeError: printme() takes exactly 1 argument (0 given)

Keyword Parameters:

Keyword arguments are related to function calls. When a keyword argument is used in a function call, the caller identifies the argument by its name.

This can skip arguments or out of order, as the Python interpreter is able to use keywords with matching values using the supplied arguments. It is also possible to make keywords call the printme() function in the following ways:

#!/usr/bin/python

# 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( str = "My string");

When the above code is executed, the following result is produced:

My string

The following example gives a clearer picture. Note that there is no relation to the parameter order here.

#!/usr/bin/python

# Function definition is here
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=50, name="miki" );

When the above code is executed, the following result is produced:

Name: miki
Age 50

Default parameters:

The default parameter is the parameter that assumes a default value if not supplied with the parameter value of the function call. The following example gives an idea of the default parameter, which will print age by default if not passed a value:

#!/usr/bin/python

# Function definition is here
def printinfo( name, age = 35 ):
  "This prints a passed info into this function"
  print "Name: ", name;
  print "Age ", age;
  return;

# Now you can call printinfo function
printinfo( age=50, name="miki" );
printinfo( name="miki" );

When the above code is executed, the following result is produced:

Name: miki
Age 50
Name: miki
Age 35

Variable length parameter:

It may be necessary to handle functions with more parameters than are specified in the definition of the function. These parameters are called variable length parameters and are not named in the function definition, unlike the required default parameters.

The general syntax for functions with non-keyword variable arguments looks like this:

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

An asterisk (*) is placed that will hold the values of all non-keyword variable arguments before the variable name. The tuple remains empty if no other parameters are specified during the function call. Here is a simple example:

#!/usr/bin/python

# Function definition is here
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 );

When the above code is executed, the following result is produced:

Output is:
10
Output is:
70
60
50

Anonymous Functions:

Small anonymous functions can be created using the lambda keyword. These functions are called anonymous because they are not declared in the standard way by using the def keyword.

  • Lambda forms can take any number of arguments, but return only one value in the expression. They cannot contain commands or multiple expressions.
  • Anonymous functions can't be called directly to print because they require lambda expressions.
  • Lambda functions have their own namespaces and cannot access variables higher than in their argument lists and those in global namespaces etc.
  • Although it seems that lambda is a one-line version of a function, they are not in C or C++, and their purpose is to allocate the equivalent of a one-line declaration by calling the stack of the passing function for performance reasons.

grammatical

The syntax of the lambda function contains only a single statement, as follows:

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

The following example shows how the function lambda form works:

#!/usr/bin/python

# Function definition is here
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 )

When the above code is executed, the following result is produced:

Value of total : 30
Value of total : 40

return statement:

This statement returns [expression] to exit the function, optionally passing back an expression to the caller. The return statement without arguments returns None.

All of the above examples do not return any values, but you can return values from a function if you like:

#!/usr/bin/python

# Function definition is here
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 

When the above code is executed, the following result is produced:

Inside the function : 30
Outside the function : 30

Scope of the variable:

All variables in a program may not be accessible from all locations in that program. This depends on the variables declared.

The scope of a variable identifies the program, which can access a specific part of an identifier. Two basic categories of variables in Python:

  • global variable
  • local variable

Global vs. local variables:

This is where variables defined inside a function body have local scope and those defined outside have global scope.

Local variables can only be declared and accessed inside a function, whereas global variables can be accessed by all functions throughout the body of the program. When a function is called, the variables declared inside it are brought into scope. Here is a simple example:

#!/usr/bin/python

total = 0; # This is global variable.
# Function definition is here
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 

When the above code is executed, the following result is produced:

Inside the function local total : 30
Outside the function global total : 0