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()
Types of Functions in Python:
Python supports two main types of functions:
- Built-in Functions:
- These are pre-defined in Python (e.g., print(), len(), range()).
- 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.
Benefits of Using Functions:
- 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.
Basic Examples:
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)