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.



Recent Posts

See All

Python Modules

A module is a file containing Python definitions and statements. A module can characterize functions, classes and variables. A module can likewise incorporate runnable code. Gathering related code int

Command Line Arguments in Python

Command Line Arguments are the arguments that are specified after the name of the program in the command line shell of the operating system. Python gives different ways of dealing with these types of