What is a function in Python?

Updated: May 18


Function is a group of related statements that perform a specific task in Python. A function is a block of code which only runs when it is called. Functions help break our program into smaller and modular fragment. As our program grows bigger and bigger, functions make it more organized and manageable. Function avoids repetition and makes code reusable.

Syntax:

def function_name(parameters):

""docstring""

statement(s)

Creating a Function:

A function is defined using the def keyword in Python:

Example

def my_function():

print("Hello dear")

Calling a Function

To call a function, use the function name followed by parenthesis:

Example

def my_function():

print("Hello dear")

my_function()


There are following steps necessary for function

· Keyword def marks the start of function header.

· A function name to uniquely recognize it.

· Parameters through which we pass values to a function. They are optional.

· A colon (:) to mark the end of function header.

· Optional documentation string (docstring) to describe what the function does.

· An optional return statement to return a value from the function.

Types of Functions

There are two types of functions which are below:

1. Built-in functions –Built in function are those functions that are built into Python.

2. User-defined functions – User defined functions are those functions which defined by the users themselves.