Function In Python Programming | Python Programming

What is a function in Python?

In Python, a function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.

Furthermore, it avoids repetition and makes code reusable.
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 the function name and parentheses ( ( ) ).
  • 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 None.

Syntax of Function
def function_name(parameters):
Above shown is a function definition which consists of following components.

  • Keyword def marks the start of the function header.
  • A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in python.
  • Parameters (arguments) through which we pass values to a function. They are optional.
  • A colon (:) to mark the end of the function header.
  • Optional documentation string (docstring) to describe what the function does.
  • One or more valid python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces).
  • An optional return statement to return a value from the function.

Example of a function
   def greet(name):
    """This function greets to
    the person passed in as
    print("Hello, " + name + ". Good morning!")

How to call a function in python?
Once we have defined a function, we can call it from another function, program or even the Python prompt. To call a function we simply type the function name with appropriate parameters.
>>> greet('Paul')
Hello, Paul. Good morning!
Note: Try running the above code into the Python shell to see the output.

The first string after the function header is called the docstring and is short for documentation string. It is used to explain in brief, what a function does.
Although optional, documentation is a good programming practice. Unless you can remember what you had for dinner last week, always document your code.
In the above example, we have a docstring immediately below the function header. We generally use triple quotes so that docstring can extend up to multiple lines. This string is available to us as the __doc__ attribute of the function.
For example:
Try running the following into the Python shell to see the output.
  1.  >>> print(greet.__doc__)
  2.  This function greets to
  3.       the person passed into the
  4.       name parameter

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
Global vs. Local variables
Variables that are defined inside a function body has 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. Following is a simple example −

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, it produces the following result −
Inside the function local total: 30
Outside the function global total :  0

The return statement
The return statement is used to exit a function and go back to the place from where it was called.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.

Syntax of return
return [expression_list]
This statement can contain an expression which gets evaluated and the value is returned. If there is no expression in the statement or the return statement itself is not present inside a function, then the function will return the None object.
For example:-
All the above examples are not returning any value. You can return a value from a function as follows −

# 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, it produces the following result −
Inside the function: 30

How the Function works in Python?

The Anonymous Functions

These 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.
·      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 an anonymous function cannot be a direct call to print because lambda 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.

Function Arguments
Here are the different types of 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 gives a syntax error as follows −
# Function definition is here
def printus( str ):
   "This prints a passed string into this function"
   print str

# Now you can call printus function
When the above code is executed, it produces the following result −
Traceback (most recent call last):
   File "", line 11, in
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments
Keyword arguments are related to the function calls. 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 −
# Function definition is here
def printus( str ):
   "This prints a passed string into this function"
   print str
# Now you can call printus function
printus( str = "My string")
When the above code is executed, it produces the following result −
My string
The following example gives more clear picture. Note that the order of parameters does not matter.

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

# Now you can call printinformation function
printinformation( age=40, name="google" )
When the above code is executed, it produces the following result −
Name:  google
Age  40
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. The following example gives an idea on default arguments, it prints default age if it is not passed −
# Function definition is here
def printinfo( name, age = 45 ):
   "This prints a passed info into this function"
   print "Name: ", name
   print "Age ", age

# Now you can call printinfo function
printinfo( age=50, name="google" )
printinfo( name="google" )
When the above code is executed, it produces the following result −
Name:  google
Age  50
Name:  google
Age  45
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.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_ple ):
   return [expression]
An asterisk (*) is placed before the variable name that holds 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 −
# Function definition is here
def printinfo( arg0, *varple ):
   "This prints a variable passed arguments"
   print "Output is: "
   print arg0
   for var in varple:
      print var

# Now you can call printinfo function
printinfo( 10 )
printinfo( 70, 60, 50 )
When the above code is executed, it produces the following result −
Output is:
Output is:

Types of Functions
Basically, we can divide functions into the following two types:

  • Built-In Function - Functions that are built into Python.
  • User Defined Function - Functions defined by the users themselves.
What are user-defined functions in Python?
Functions that we define ourselves to do certain specific task are referred as user-defined functions. The way in which we define and call functions in Python are already discussed.
Functions that readily come with Python are called built-in functions. If we use functions written by others in the form of library, it can be termed as library functions.
All the other functions that we write on our own fall under user-defined functions. So, our user-defined function could be a library function to someone else.
Advantages of user-defined functions
  • User-defined functions help to decompose a large program into small segments which makes program easy to understand, maintain and debug.
  • If repeated code occurs in a program. Function can be used to include those codes and execute when needed by calling that function.
  • Programmars working on large project can divide the workload by making different functions.

Example of a user-defined function

# Program to illustrate
# the use of user-defined functions
def add_numbers(x,y):
   sum = x + y
   return sum
num1 = 5
num2 = 6
print("The sum is"add_numbers(num1num2))
Enter a number: 2.4
Enter another number: 6.5
The sum is 8.9
Here, we have defined the function my_addition() which adds two numbers and returns the result.
This is our user-defined function. We could have multiplied the two numbers inside our function (it's all up to us). But this operation would not be consistent with the name of the function. It would create ambiguity.
It is always a good idea to name functions according to the task they perform.
In the above example, print() is a built in function in Python

Built in Function In Python

The builtins module is automatically loaded every time Python interpreter starts, either as a top level execution environment or as interactive session. The Object class, which happens to be the base class for all Python objects, is defined in this module. All built-in data type classes such as numbers, string, list etc are defined in this module. The BaseException class, as well as all built-in exceptions, are also defined in it. Further, all built-in functions are also defined in the built-ins module.
Since this module is imported in the current session automatically, normally it is not imported explicitly. All the built-in functions used in the executable code are by default considered to be from built-ins module. 
In Python 3.6 (latest version), there are 68 built-in functions. They are listed below alphabetically along with brief description.
Python abs()
returns absolute value of a number
Python all()
returns true when all elements in iterable is true
Python any()
Checks if any Element of an Iterable is True
Python ascii()
Returns String Containing Printable Representation
Python bin()
converts integer to binary string
Python bool()
Converts a Value to Boolean
Python bytearray()
returns array of given byte size
Python bytes()
returns immutable bytes object
Python callable()
Checks if the Object is Callable
Python chr()
Returns a Character (a string) from an Integer
Python classmethod()
returns class method for given function
Python compile()
Returns a Python code object
Python complex()
Creates a Complex Number
Python delattr()
Deletes Attribute From the Object
Python dict()
Creates a Dictionary
Python dir()
Tries to Return Attributes of Object
Python divmod()
Returns a Tuple of Quotient and Remainder
Python enumerate()
Returns an Enumerate Object
Python eval()
Runs Python Code Within Program
Python exec()
Executes Dynamically Created Program
Python filter()
constructs iterator from elements which are true
Python float()
returns floating point number from number, string
Python format()
returns formatted representation of a value
Python frozenset()
returns immutable frozenset object
Python getattr()
returns value of named attribute of an object
Python globals()
returns dictionary of current global symbol table
Python hasattr()
returns whether object has named attribute
Python hash()
returns hash value of an object
Python help()
Invokes the built-in Help System
Python hex()
Converts to Integer to Hexadecimal
Python id()
Returns Identify of an Object
Python input()
reads and returns a line of string
Python int()
returns integer from a number or string
Python isinstance()
Checks if a Object is an Instance of Class
Python issubclass()
Checks if a Object is Subclass of a Class
Python iter()
returns iterator for an object
Python len()
Returns Length of an Object
Python list() Function
creates list in Python
Python locals()
Returns dictionary of a current local symbol table
Python map()
Applies Function and Returns a List
Python max()
returns largest element
Python memoryview()
returns memory view of an argument
Python min()
returns smallest element
Python next()
Retrieves Next Element from Iterator
Python object()
Creates a Featureless Object
Python oct()
converts integer to octal
Python open()
Returns a File object
Python ord()
returns Unicode code point for Unicode character
Python pow()
returns x to the power of y
Python print()
Prints the Given Object
Python property()
returns a property attribute
Python range()
return sequence of integers between start and stop
Python repr()
returns printable representation of an object
Python reversed()
returns reversed iterator of a sequence
Python round()
rounds a floating point number to ndigits places.
Python set()
returns a Python set
Python setattr()
sets value of an attribute of object
Python slice()
creates a slice object specified by range()
Python sorted()
returns sorted list from a given iterable
Python staticmethod()
creates static method from a function
Python str()
returns informal representation of an object
Python sum()
Add items of an Iterable
Python super()
Allow you to Refer Parent Class by super
Python tuple() Function
Creates a Tuple
Python type()
Returns Type of an Object
Python vars()
Returns __dict__ attribute of a class
Python zip()
Returns an Iterator of Tuples
Python __import__()
Advanced Function Called by import

Post a Comment