Python Functions with examples



Hello dear readers! Welcome back to another edition of our tutorial on Python. In this tutorial guide, we are going to be studying about the Python Functions.

A function is a block of organized and reusable code that is used in performing a single, related action. Functions gives better modularity for your application and a high rate of code reuse.

As you already know, Python gives you various built-in functions like print(), etc. but you can also create your own functions. These created functions are called user-defined functions.

Defining a Function

You can define functions to give the required functionality. Below are some rules to define a function in Python.

  • Function blocks starts with the keyword def and after that, followed by the function name and parentheses (()).
  • First statement of a function can be optional statement - the documentational string of the function or docstring.
  • Any input parameters or arguments should be placed in parentheses. You can also define parameters inside of these parentheses.
  • The code block within every function start with a colon (:) and is indented.
  • The Python statement return [expression] is used to exit a function, optionally passing back an expression to the caller. A return statement that has no arguments is the same as return None.


Syntax

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

By default, the parameters do have a positional behavior and you need to inform them in same order that they were defined.

Example

The following function takes a string as an input parameter and then prints it on standard screen.

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

Calling a Function

Defining a function in Python only gives a name to it, specifies all the parameters that are to be included in the function and structures the block of code.

As soon as the basic structure of a function is finally concluded, you can execute it by calling it from another function or you can do it directly from the Python prompt.

Example

The following is an example to 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")

Output

Below is the output of the above example -

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


Pass by reference vs value

All the parameters (arguments) in Python are passed by reference. It simply means that if you change what a parameter refers to within a function, the change also reflects back in the calling function.

Example

The following below is a simple example -

#!/usr/bin/python

# Function definition is here
def changeme( mylist ):
   "This changes a passed list into this function"
   mylist.append([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

Output

From the above example we are just maintaining reference of the passed object and then appending values in the same object. So, this will produce 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 is one more example below where argument is being passed by reference and the reference is being overwritten inside the called function -

#!/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

Here, the parameter mylist is local to the function that is named changeme. Changing mylist within the function does not affect mylist. This function ends up achieving nothing and the following result will be produced -

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

RECOMMENDED: Python Numbers


Python Function Arguments

You can call a function using the following forms arguments -

  • Required arguments
  • Keyword arguments
  • Default arguments
  • Variable-length arguments

Required arguments

Python required arguments are the arguments passed to a function in a 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 will need to pass one argument, otherwise it gives a syntax error 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()

Output

When the above code is executed, it will produce the following result -

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


Keyword argument

Keywords arguments are related to the function calls. Whenever you use keyword arguments in a function call, the caller spots the arguments through the parameter name.

This allows you to skip arguments or even place them out of order because the Python's interpreter is able to use the keywords that are provided to match the values with parameters. You can as well make the keyword calls to 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")

Output

When the above code is executed, it will produce the following result -

My string

Following example below gives a more clearer picture. Note that the sequence of parameters does not matter -

#!/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=20, name="paul" )

Output

When the above code is executed, it will produce the following result -

Name:  paul
Age  20


Default arguments

A Python default argument is the argument which takes up a default value if no value was ever being provided in the function call for that argument.

Example

The following example gives an idea on default arguments, it prints the default age if it not passed -

#!/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=20, name="paul" )
printinfo( name="paul" )

Output

When the above code is executed, it will produce the following result -

Name:  paul
Age  20
Name:  paul
Age  35

Variable-length arguments

A situation might arise where you may need to process a function for more arguments than you already specified while defining a function. These new arguments are called the variable length arguments and are not named in the function definition.

Syntax

The syntax for a function with non-keyword variable arguments is this -

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

An asterisk (*) is placed before the variable name which contains the values of the code's non-keyword variable arguments. This tuple will remain empty if no additional arguments are specified during the function call.

Example

Following 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 )

Output

When the above code is executed, it will produce the following result below -

Output is:
10
Output is:
70
60
50


The Anonymous Functions

These Python functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions.

  • The lambda forms can take any numbers of arguments but returns just a value in the form of an expression. They cannot hold any commands or multiple expressions.
  • An anonymous function can't be a direct call for printing because lambda requires an expression.
  • Lambda functions have their own local namespace and can't access variables other than those in their parameter list and those in the global namespace.
  • Although it does appear that lambdas are a 1-line version of a function, they are not similar to inline statements in C or C++, whose purpose is passing the function stack allocation during invocation for performance reasons.

Syntax

The syntax of the lambda function contains only a single statement, which is as follows -

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

Example

Following is the example to how lambda form of function actually 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 )

Output

When the above code is executed, it will produce the following result -

Value of total :  30
Value of total :  40



The return Statement
The Python return statement exits a function, that optionally passes back an expression to the function caller. A return statement with no arguments is the same as return None.

Example
All the above examples above are not returning any value. You can retire a value from a function as follows -

#!/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 

Output
When the above code is executed, it will produce the following result -

Inside the function :  30
Outside the function :  30



Scope of Variables
All variables in a program may not be accessible at all the locations in that program. This depends on where you have declared the variable.

The variable scope determines the portion of the program where a particular identifier in the program can be accessed. In Python, there are two basic scopes of variables -

  • Global variables
  • Local variables

Global vs. Local variables
Variables that are defined inside a function body have a local scope, and those that are defined outside have a global scope.

This means that the local variables can be accessed only inside the function that they are declared, whereas the global variables can be accessed through out the body of the program by all functions. Whenever you call a function, the variables declared inside of it are brought into scope.

Example
Following 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 

Output
When the above code is executed, it will produce the following result -

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


Alright guys! This is where we are rounding up for this tutorial guide. In our next tutorial, we are going to be discussing about the Python Modules.

Feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.