Functions in python

Functions

Functions are reusable pieces of code. They allow you to give a name to a block of statements, allow you to use the functionality of the block any number of times in your program. This is known as calling the function.

The Concept of Functions is very Important in any programming language . So we will study it in deep in this lesson.

In PYTHON Functions are defined using the def keyword. After this keyword comes the name for the function, followed by a pair of parentheses which may have some names of variables, and followed by a colon in the end of the line . Next follows the block of statements that are part of this function. An example will show the implementation of the function and it is actually easy to describe Function in Python.

def hello():
    # block belonging to the function
    print('hello world')
# End of function

hello()  # call the function
hello()  # call the function again

output

hello world
hello world

How It Works

We define a function called hello using the syntax explained above. This function takes no parameters and hence there are no variables present inside the parentheses. Parameters to functions are just the input to the function so that we can pass in different values to it and get back corresponding results to that input.

Notice that we can call the same function twice which means we do not have to write the same code again and again we simply refer to that function and it works.

Function Parameters

A function can take parameters, which are values we supply to the function so that the function can do things in accordance to those values.

Parameters are specified within the pair of parentheses in the function definition, separated by commas. When we call the function, we supply the values in it.

def print_max(a, b):
    if a > b:
        print(a, 'is maximum')
    elif a == b:
        print(a, 'is equal to', b)
    else:
        print(b, 'is maximum')

# directly pass the values
print_max(3, 4)

x = 5
y = 7

# pass variables as arguments
print_max(x, y)

output

4 is maximum
7 is maximum

How It Works

Here, we define a function called print_max that uses two parameters called a and b.In this function we try to find out the greater number between the given Two Parameters by using simple If–Else statements.

The first time we call the function print_max, we directly supply the values in it. In the second case, we call the function with variables as arguments. print_max(x, y) causes the value of argument x to be assigned to parameter a and the value of argument y to be assigned to parameter b. The print_max function works the same way in both cases.

NOTE: We do not need to write the statements twice we simply create a function and refer to the function when we need.