Python                                                          Home : www.sharetechnote.com

 

 

 

 

Python - Function Define

 

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

 

 

< 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