Introduction to python functions:

In this article, We are going to learn what is python function? Different types of python functions. How to write and call python function in a program.

So let’s get started with the definition of python function.

syntax of functions in python

What is python function?

Function in python is a collection of related statements which are used to perform a specific task and return the result or value to the caller of the function. It basically breaks our code into smaller and modular chunks of code and it is possibles to call and execute these code blocks within the program. In simple words the python function is a block of well organised and reusable code.

Function in python helps us to keep our code neat and manageable. It increases the readability and re-usability of code.

Without use of functions it will be very difficult to reuse the code. The only alternative to reuse the code is to copy the same code at different places in program. Eventually the maintenance of such code will be the most difficult task i.e We have to find each and every location where we have copied the same code and modify it. Therefor use of python function is the best approach for reusing the code.

Types of function:

In python there are two basic types of functions.

  • Built-In Functions: These are the functions which are already defined in python. We don’t need to define them rather we can directly call them into our program. Python functions like print(), input() are some of the examples of python build-in function types.
  • User Defined Functions: If there is no suitable built-in function available for our requirement. Then there is a provision for defining our own python function. However while writing/defining new user defined function there is specific syntax which we have to follow. Below is the syntax for writing user defined function.

Syntax of python user defined function:

def function_name(parameters/arguments):
    """Function docstring (optional)"""
    statements
    return [expressions]

Above is the syntax using which we can write our own user defined function. Let’s understand the significance of each word in the syntax.

  • def: Keyword “def” tells the interpreter that, It is the start of new function header.
  • “def” keyword is followed by the unique function name. Unique function name is a mandatory thing so that interpreter can differentiate between functions present in program.
  • parameters/arguments: These are the inputs given to the function. These are the optional inputs, So if a function don’t need any kind of input then you can keep the parenthesis empty. Arguments must be provided within the parenthesis.
  • Colon:” marked at the end of function lets the interpreter understand the end of function header.
  • Function docstring: It is the documentation string (comment) used to describe about what this function is doing. It is a good practice to write the docstring.
  • statements: These are the actual modular code lines which we want to reuse. They are separated from other code using some level of indentation.
  • return: This statement tells the interpreter that, It is the end of function. After the return statement program gets back to the place from where the function is called. This statement returns the result/value of the function to the caller of function. It is an optional statement.

Example of function:

Example 1: Python function to perform addition of two numbers.

def addition(x, y):
    """This function adds number x and y and returns sum 'z' to the user."""
    z = x + y
    return z

How to call a function in python:

Now we have our python function defined with us and we want to call it in our program.

Calling any function is very easy task, Simply write the name of function along with required input parameters/arguments.

We can call a function from other function, program or even in command prompt.

Example 1: Python function for addition of two numbers.

#Function definition.
def addition(x, y):
    """This function adds x and y and returns sum 'z' to the user."""
    z = x + y
    return z

x = int(input("Please enter first number:"))
y = int(input("Please enter second number:"))
#Calling a function addition.
print("Addition of first and second number is:", addition(x, y))

#Result
Please enter first number:6
Please enter second number:8
Addition of first and second number is: 14

In above example, We are having first four lines of code that defines the function named “addition”. This function requires two integer numbers (x and y) as argument/parameters. This addition function performs the addition of input parameters and stores it into variable “z”. Last line in the function returns the addition of two numbers i.e variable “z”.

After defining the function there three lines present. First two lines are for getting the integer input from user (i.e number x and y). Third line in the code (print function) calls the addition function and prints the result returned from the addition function.

Example 2: If and else statements in python function. (Python program to check odd and even numbers.)

#Function definition.
def number_check(input_number):
    """This function checks whether the number is odd or even."""
    if input_number % 2 == 0:
        return print(input_number, "is a even number!")
    else:
        return print(input_number, "is an odd number!")

input_number = int(input("Please enter a number to check:"))
#Calling a function number_check.
number_check(input_number)
#Result:
Please enter a number to check:45
45 is an odd number!

Scope of variables in python:

In python program we can define the variables at different places i.e Inside the function and outside the function. Accessibility of a variable depends upon where you have declared the variable in program. All the variables defined in a program may not be accessible from all the places

Depending upon the scope of variable declaration, There are two types of variable;

  • Global variables: As the name suggest these variables are globally accessible i.e they can be accessed from any part of program. They are declared outside the function body, Therefore they can be accessed by any function or program.
  • Local Variables: These types of function have limited scope. They are declared within the function so only that specific function can have the access of it. Other functions or programs can’t access it.

However if you want to access the local variables outside the function. you can do so by declaring them global using “global” keyword.

Example 3: Python program to print local and global variables.

#Function definition.
def print_number():
    """This function prints the number number_variable."""
    number_variable = 10
    return print("Value of variable within the function (Local variable) is:", number_variable)

#Calling a function print_number.
print_number()
number_variable = 15
print("Value of variable total outside function (Global variable) is:", number_variable)

#Result:
Value of variable within the function (Local variable) is: 10
Value of variable total outside function (Global variable) is: 15

In above python program, We are having variable named “number_variable” declared at two different places. One is within the function (local scope) and other is outside the function (Global scope).

Although the name of both these variable is same but since their scope is different (Global and local) they will be treated as two different variables by the interpreter.

Continue Reading:

Share this Post

Leave a Comment

Your email address will not be published.