Python

 

 

 

 

Python - Function Define

 

Functions are reusable blocks of code that perform a specific task. They are used to break down complex problems into smaller, more manageable parts, which can be reused throughout a program. Functions help improve the readability, maintainability, and modularity of your code.

 

To define a function in Python, you use the def keyword, followed by the function name, a pair of parentheses containing the function's parameters, and a colon. The code block that follows, indented under the function definition, is the body of the function. This is where the actual logic of the function is implemented. Here's a general outline of a function definition:

    def function_name(parameters):

        # Code block (function body)

        # Perform some operation(s) using the parameters

        # Return a value (optional)

  • def keyword: This keyword is used to indicate the start of a function definition.
  • Function name: The name of the function should be descriptive and follow Python's naming conventions, which is usually lowercase with words separated by underscores.
  • Parameters: These are the input values that the function takes when it is called. Parameters are optional, and a function can have zero or more parameters. When defining a function, you list the parameter names inside the parentheses, separated by commas. When calling the function, you provide the corresponding arguments for each parameter.
  • Function body: The indented block of code that follows the function definition is the function body. This is where you implement the logic of the function, using the parameters as needed.
  • return statement: A function can return a value to the caller using the return keyword, followed by the value or expression to be returned. This is optional, and if no return statement is present, the function returns None by default.

To use a function, you call it by its name, followed by parentheses containing the arguments that correspond to the function's parameters. The function executes its body, performs the specified operations, and optionally returns a value.

 

 

 

Examples

 

NOTE 1 : All the examples in this page are written in Python 3.x. It may not work if you use Pyton 2.x

NOTE 2 : All the examples in this page are assumed to be written/run on Windows 7 unless specifically mentioned. You MAY (or may not) need to modify the syntax a little bit if you are running on other operating system.

  • Function with No parameter and No Return - Example 1
  • Function with parameters and single return - Example 2
  • Function with parameters and multiple return - Example 3
  • Function with parameters and multiple return - Example 4
  • Function with Variable Number of Parameters - Example 5
  • Function with Variable Number of Parameters with Empty Parameter Handling - Example 6  
  • Function with Variable Number of Parameters with referencing Argument Elements - Example 7  
  • Function call with named Argument  - Example 8
  • Functions with Default Argument Value - Example 9

 

 

< Syntax >

 

def functionName(parameters) :

     functionBody

return [values]

 

 

< Examples >

 

< Example 1 > Function with No parameter and No Return

 

#define a function

def printMessage() :

    print("Message : Function Call Success")    

    return

 

#calling the function

printMessage()

 

Result :-----------------

 

Message : Function Call Success

 

 

< Example 2 >  Function with parameters and single return

 

#define a function

def add(a,b) :

    c = a + b   

    return c

 

#calling the function

print("2 + 3 =",add(2,3))

 

Result :-----------------

 

2 + 3 = 5

 

 

< Example 3 >  Function with parameters and multiple return

 

#define a function

def ToUpperLower(aString) :

    strUpper = aString.upper()  

    strLower = aString.lower()

    return [strUpper,strLower]

 

#calling the function

myStr = "Hello World"

ulStr = ToUpperLower(myStr)

print("Upper Case = ",ulStr[0])

print("Lower Case = ",ulStr[1])

 

Result :-----------------

Upper Case =  HELLO WORLD

Lower Case =  hello world

 

 

< Example 4 >  Function with parameters and multiple return  

 

def AddDiff(a,b):

    add = a + b

    diff = a - b

    return add, diff

 

add,diff = AddDiff(2,3)

print(add," ",diff)

 

(add,diff) = AddDiff(2,3)

print(add," ",diff)

 

r = AddDiff(2,3)

print(r, " ", r[0], " ",r[1])

 

 

Result :-----------------

 

5   -1

5   -1

(5, -1)   5   -1

 

 

< Example 5 > Function with Variable Number of Parameters

 

def printMessage(Msg, *values):

    print(Msg ," : ",values)

 

printMessage("This is the message with the value of")    

printMessage("This is the message with the value of", 2)

printMessage("This is the message with the value of", 2,3,4)

printMessage("This is the message with the value of", [2,3,4])

printMessage("This is the message with the value of", {2,3,4})

 

 

Result :-----------------

 

This is the message with the value of  :  ()

This is the message with the value of  :  (2,)

This is the message with the value of  :  (2, 3, 4)

This is the message with the value of  :  ([2, 3, 4],)

This is the message with the value of  :  ({2, 3, 4},)

 

 

< Example 6 > Function with Variable Number of Parameters with Empty Parameter Handling

 

def printMessage(Msg, *values):

    if not values:

        print(Msg)

    else:    

        print(Msg ," : ",values)

 

printMessage("This is the message with the value of")    

printMessage("This is the message with the value of", 2)

printMessage("This is the message with the value of", 2,3,4)

printMessage("This is the message with the value of", [2,3,4])

printMessage("This is the message with the value of", {2,3,4})

 

 

Result :-----------------

 

This is the message with the value of

This is the message with the value of  :  (2,)

This is the message with the value of  :  (2, 3, 4)

This is the message with the value of  :  ([2, 3, 4],)

This is the message with the value of  :  ({2, 3, 4},)

 

 

< Example 7 >  Function with Variable Number of Parameters with referencing Argument Elements

 

def printMessage(Msg, *values):

    if not values:

        print(Msg)

    else:    

        print(Msg ," : ")

        for v in values :

            print("   v =",v)

 

printMessage("This is the message with the value of")    

printMessage("This is the message with the value of", 2)

printMessage("This is the message with the value of", 2,3,4)

printMessage("This is the message with the value of", [2,3,4])

printMessage("This is the message with the value of", {2,3,4})

 

 

Result :-----------------

 

This is the message with the value of

This is the message with the value of  :

   v = 2

This is the message with the value of  :

   v = 2

   v = 3

   v = 4

This is the message with the value of  :

   v = [2, 3, 4]

This is the message with the value of  :

   v = {2, 3, 4}

 

 

< Example 8 >  Function call with named Argument

 

def printMessage(Msg,values):

    print(Msg ," : ",values)

 

 

# if you pass all the argument, you don't have to care of the order of the

# argument

# NOTE : You can use the named argument for some parameter and use the non-named

# argument for some other parameter if you be careful of the order. But I would

# not recommend you to use the mixture of named and non-named argument.

printMessage(Msg = 'This is the message with the value of',values = 2)    

printMessage(values = 2, Msg = 'This is the message with the value of')  

 

Result :-----------------

 

This is the message with the value of  :  2

This is the message with the value of  :  2

 

 

< Example 9 >  Functions with Default Argument Value

 

def printMessage(Msg=None,values=None):

    print(Msg ," : ",values)

 

# with the combination of default argument value and named argument passing

# you can use the function in very flexible ways

printMessage()

printMessage(Msg = 'This is the message with the value of')

printMessage(values = 2)

printMessage(Msg = 'This is the message with the value of',values = 2)    

printMessage(values = 2, Msg = 'This is the message with the value of')

 

Result :-----------------

 

None  :  None

This is the message with the value of  :  None

None  :  2

This is the message with the value of  :  2

This is the message with the value of  :  2

 

 

< Example 10 >