What is a function in Python?

Updated: May 18, 2020


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.



14 views0 comments

Recent Posts

See All

Tell () function can be used to get the position of file handle and returns current position of file object where as Seek () function is used to change the position of the file handle to a given speci

Seek () function is used to change the position of the file handle to a given specific position in python. File handle such as a cursor which defines from where the data has to be read or written in t

Slicing is a Python attitude that enables accessing parts of data from the given sequence like list, tuples etc. A slice object is created based on a set of indices. Slicing starts anywhere from list