Table of contents

Function

  • The function is the set of instructions to perform a specific task, nothing but functions.
  • A subprogram or a smaller part of the main program.
  • A block of code that performs a specific task and can be called when needed.
  • Perform specific operations.
  • Promote code reusability, allowing the same block of code to be used multiple times without rewriting.

Using functions in programming provides several benefits:

  • Reduced Development Time: Modular code is faster to write and maintain.
  • Lower Memory Usage: Reusing functions avoids duplicating code.
  • Faster Execution: Optimized, reusable code can improve performance.
  • Improved Performance: Modular design enhances application efficiency.
  • Minimized Code Redundancy: Avoids repetitive code, making programs cleaner and easier to maintain.

Functions in Python consist of two main components:

  • Function Definition: Defines the function’s name, parameters, and the code block to execute.Created using the def keyword.Exists only once in the program.
  • Defines the function’s name, parameters, and the code block to execute.
  • To create function using the def keyword.
  • Exists only once in the program.
  • Function Calls: Invokes the function to execute its code.Can occur multiple times in the program.Requires a corresponding function definition, or a NameError will occur.
  • Invokes the function to execute its code.
  • Can occur multiple times in the program.
  • Requires a corresponding function definition, or a NameError will occur.
# Creating function def hello(): function defintion print("Hello Cedlearn") # function body hello() # function calling

Every function typically involves three phases:

  • Input: Accepts data (parameters or arguments) to process.
  • Process: Performs operations on the input data.
  • Output: Returns a result or produces an effect (e.g., printing, modifying data).