What are Functions in Python?

Python Functions are very easy to write in python and all non-trivial programs will have functions. Function names have the same rules as variable names. The function is a block of related statements designed to perform a computational, logical, or evaluative task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over and over again.

Functions can be both built-in or user-defined. It helps the program to be concise, non-repetitive, and organized.

  • Syntax:

def function_name(parameters): """docstring""" statement(s) return expression

  • Creating a Function: We can create a Python function using the def keyword.

Example:

# A simple Python function def fun(): print("Hello World")

* **Calling a Function**: After creating a function we can call it by using the name of the function followed by parenthesis containing parameters of that particular function.

Example:

# A simple Python function def fun(): print("Hello World") # Driver code to call a function fun()

Output:

Hello World