Python Functions

A Function is a block of code that only runs when it is called. Python Functions are a group of related statements that performs a specific task. Python Functions are used in the matter where a code is needed again and again. So, writing it repeatedly, we just have to call the function. Due to this, a program seems to be more precise and organized. Python Functions can be both built-in or user-defined.

Here are some rules to define a function in any Python program,
  • The code block inside every function starts with a colon (:).
  • Function blocks start with the keyword def which is followed by the function name and parentheses ( ( ) ).
  • These parentheses contain any input parameters or arguments. Through Parameters, we pass values to the function. they are optional.
  • The first statement of a function can be an optional statement – the documentation string of the function or docstring.
  • An optional return statement is used to return a value from the function.
  • 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 a return None.
  • Parameters (arguments) through which we pass values to a function. They are optional.
Syntax of Python Function is as given below,

Example of Python Functions:

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

Calling a Function:

By defining a function we give it a name, specifies the parameters, and structure the blocks of code. Once the fundamental structure of a function is finalized, you’ll be able to execute it by calling it from another function or specifically from the Python prompt. starting from a simple example,

# Function definition
def function1():
  print("Python function")


Python Function Arguments:

Given below are some types of formal arguments which can be call a function,

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

Required arguments:

Arguments that passed to a function in correct positional order are known as Required Arguments. Function definition and the number of arguments in the function call should be the same. definition.

To call the function print(), you definitely need to pass one argument, otherwise it gives a syntax error as given below,

#Function definition
def function1( string ):
   "This prints a passed string into this function"
   print string

#Now call function1 function

Variable-length arguments:

Normal and keyword variable number of arguments can be used. An asterisk (*) is placed before the variable name that holds the values of all non-keyword variable arguments.


#function definition
def function5( argument, *vartuple ):
   "This prints a variable passed arguments"
   print "Output is: "
   print argument
   for var in vartuple:
      print var

#call function5 function
function5( March )
function5( June, July )

Default arguments:

In some situations, there is no value has been assigned to the function. in that situation Default argument is the argument which assumes a vale for that function. To provide a default value to an argument the assignment operator (=) has been used.

#default argument

def Fun(x, y=Alice):
    print("x: ", x)
    print("y: ", y)
#Driver code (call Fun() with only argument)

Keyword arguments:

The arguments which are related to the function call are known as Keyword arguments. When keyword arguments are used in a function call, the arguments are identified by the parameter name. Due to these, we can 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. When a function is called with some values, these values get assigned to the arguments according to their position.

#program for Keyword Arguments
def studID(Name, Rollno):
    print(Name, Rollno)
#Keyword arguments
studID(Name= 'Alice', Rollno='1088')
studID(Rollno='1088', Name='Alice)

Anonymous Functions: 

In Python functions there are some functions that are not declared in the program by using the def keyword, These functions are called Anonymous Functions. These functions are declared by using the lambda keyword which is used to create small anonymous functions.

Syntax for lambda keyword in Python,

Here is the Example for better understanding,

#Function definition
subtraction = lambda arg1, arg2: arg1 - arg2;

#call subtraction as a function
print "Value : ", subtraction( 50, 40 )
print "Value : ", subtraction( 80, 50 )

Pass by reference or by value:

In Python Functions, every variable name is a reference. Every time when a variable is passed to a function, a new reference is created to the object. All parameters/arguments in the Python language are passed by reference. It states that if the parameter is being changed in a function then it will affect the calling function.

Try this Example for better understanding,

#new list with pass by reference

markslist = ["89", "70","79"]

#Function for adding an item to the list

def addmarks(mymarksList):

#Print original list


Return Statement:

The statement can be used inside a function/method to send the function’s result back to the caller known as a Return statement. The return value of a Python function can be any Python object. As everything in Python is an object.

This return statement consists of the return keyword followed by an optional return value. The statements after the return statements are not executed. One important thing is the Return statement can not be used outside the function.

#Function definition 
def multiply( arg1, arg2 ):

#Add both parameters and return them."
  product = arg1 * arg2
   print "Inside the function : ", product
   return product;

#call multiply function
product = multiply( 11, 11 );
print "Outside the function : ", product

Scope of Variables:

A variable is a label or a name given to a certain location in memory. This area holds the value you need your program to keep in mind, for utilize afterward on.

In Python functions, there is a portion of a program where the variable is recognized which is known as the Scope of the variable. Parameters and variables defined inside a function are not visible from outside the function. Hence, they have a local scope. 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 Variables:

Variables that are defined outside a body called Global variables.

#function definition
 value = 000
def funct1():
 value = 555 
print("The value is:",value )

Local variables:

Variables that are defined inside a function body called Local variables.

#function definition
def funct1():
#Global variables
String = "Tutorials Art"