Python Function

A function can be defined as the organized block of reusable code, which can be called whenever required. It is a group of related statements that performs a specific task.

Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable. It contains the set of programming statements enclosed by {}. A function can be called multiple times to provide reusability and modularity to the Python program.

It makes the program more organized.

Python provide us various inbuilt functions like range() or print(). Although, the user can create its functions, which can be called user-defined functions.

Syntax:

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

Defining a Function:

Here are some rules for defining a function.

  1. Keyword def(It is use to define a function) that marks the start of function along with its name & parentheses ( ( ) ).
  2. A function name to uniquely identify the function. It follows  the same rules of writing identifiers in Python for naming.
  3. Any input parameters or arguments should be placed within these parentheses but they are optional.
  4. Colon (:) in the end marks the end of header.
  5. Docstring is used to define what the function does. It is also optional.
  6. One or more valid python statements that make up the function body. Statements must have the same indentation level.
  7. Also a return statement to return none or value to the function.

Calling a function:

Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.

After the function is created, we can call it from another function. A function must be defined before the function call; otherwise, the Python interpreter gives an error.

We can call a function from Python prompt.

To call the function, use the function name followed by the parentheses.

Example:

def welcome(name):
    print("Welcome to ProgramsBuzz!!! "+ name)
    
welcome("Tom")  

Output:

Welcome to ProgramsBuzz.com!!! Tom

Advantage of Function

  • Using functions, we can avoid rewriting the same logic/code again and again in a program.
  • We can call Python functions multiple times in a program and anywhere in a program.
  • We can track a large Python program easily when it is divided into multiple functions.
  • Reusability is the main achievement of Python functions.
Tags