Functions in Python

Python can help you to add lines of code in one block. You can assign a meaningful name to your code and that block can perform one particular task for you. This code block is called Function or Method. Python provides some builtin functions, some of them you have already used, for example: print function. Definition of the function is as follow.

def name_of_function():
    code block here 

Function always starts with def then name of the function, “:” colon and body of the code. See following example:

def myFunction():
    print ("Hello World from Function")

You have successfully created myFunction() which can print a message, this function can be called by its name.


## Hello world from Function

it is very easy, just call the name of the function with two small brackets.

One important thing you must know, when interpreter parse the Python file, it does not execute the function code, function body will only execute when it will be called by its name.

print("Hello World before function")

def myFunction():
    print("Hello world from function")

print("Hello World after function")


## Hello world before function
## Hello world after function
## Hello world from function


Function with return value

You can perform some tasks in function and return the result.

def add():
    return 3 + 4

result = add()
print("result is ",result)

In add function, 2 integers values are added and sum of this addition is returned. Variable result contains the returned value, you can print the output and check the result. See another example: 

def multiply():
    return 3 * 4

result = multiply()
print("3 * 4 = ",result)

Function with parameters

You can pass one two or more parameters to the function.

def name_of_function(param1,param2,....):
    code block here 

See following example, you can pass two parameters to the add function, add them and return this value.

def add(a,b):
    c = a + b
    return c

Now you can call this function as many time as you want by passing different values to the function.


Do some experiment, create multiply function, pass 3 variables as a parameter, multiply them and return its result.

Here is a very interesting example, following function takes integer variable as an input and gives result with the help of if else.

def getvalue(answer):
    if answer == 1:
        return 'ONE'
    elif answer == 2:
        return 'TWO'
    elif answer == 3:
        return 'THREE'
    elif answer == 4:
        return 'FOUR'
    elif answer == 5:
        return 'FIVE'
    elif answer == 6:
        return 'SIX'
    elif answer == 7:
        return 'SEVEN'
    elif answer == 8:
        return 'EIGHT'
    elif answer == 9:
        return 'NINE'

Pass different numbers between 1 to 9 to getvalue() function and it will return the string value accordingly.