Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Functions
  5. Function in Python

Function in Python

A function in Python is a reusable block of organized, self-contained code that is written to perform a specific task when it is called.

  • Instead of writing the same code multiple times, we can define it once inside a function and reuse it as needed.
  • This helps reduce redundancy and enhances readability and modularity in programs.
  • It helps in organizing code, reducing repetition, and making programs easier to understand and maintain.

Example: Here, greet() is a function that, when called, prints “Hello, Python!”.

def greet():
    print("Hello, Python!")
    
greet()

Python supports two main types of functions:

  1. Built-in Functions:
    • These are pre-defined in Python (e.g., print(), len(), range()).
  1. User-defined Functions:
    • Functions created by the programmer using the def keyword.

Other Classifications Based on Use:

  • Function with No Arguments and No Return Value
  • Function with Arguments but No Return Value
  • Function with Arguments and Return Value
  • Lambda Functions – Anonymous, one-line functions.
  • Recursive Functions – A function that calls itself.
  • Code Reusability – Define once, use multiple times.
  • Modularity – Break down complex problems into smaller parts.
  • Improved Readability – Logical structure makes code easier to follow.
  • Debugging Made Easier – Isolating code in functions helps in identifying bugs.
  • Efficient Collaboration – Teams can work on different functions independently.

1.) Function without Parameters:

def say_hello():
    print("Hello!")
say_hello()

2.) Function with Parameters:

def greet(name):
    print(f"Hello, {name}!")
greet("Alice")

3.) Function with Return Value:

def add(x, y):
    return x + y
result = add(5, 3)
print(result)

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *