Defining Functions in Python
#Defining Functions in Python
Functions are one of the most important building blocks in Python programming. They allow developers to organize code into reusable, modular pieces that make programs more readable, maintainable, and efficient. In this article, weโll explore how to define functions in Python, their syntax, types, and best practices with examples.
A function is a block of reusable code that performs a specific task. Instead of writing the same code multiple times, you can define a function once and call it whenever needed.
def function_name(parameters):
"""docstring (optional): describes the function"""
# function body
return value
def
โ keyword to define a function.
function_name
โ user-defined name for the function.
parameters
โ optional values passed to the function.
return
โ used to return a value (optional).
def greet(name):
"""This function greets the user by name"""
return f"Hello, {name}!"
print(greet("Alice"))
Output:
Hello, Alice!
Python provides many built-in functions like len()
, print()
, sum()
, etc.
Example:
numbers = [1, 2, 3, 4]
print(len(numbers)) # Output: 4
Functions created by the programmer.
Example:
def add(a, b):
return a + b
print(add(5, 3)) # Output: 8
def power(base, exponent=2):
return base ** exponent
print(power(4)) # Output: 16 (default exponent = 2)
print(power(4, 3)) # Output: 64
*args
and **kwargs
)def display(*args, **kwargs):
print("Arguments:", args)
print("Keyword Arguments:", kwargs)
display(10, 20, 30, name="Alice", age=25)
Small, single-line functions using lambda
.
square = lambda x: x * x
print(square(5)) # Output: 25
print()
displays output on the screen.
return
sends the result back to the caller for further use.
Example:
def multiply(a, b):
return a * b
result = multiply(4, 5)
print(result) # Output: 20
โ
Use descriptive names for functions.
โ
Write docstrings to describe the purpose.
โ
Keep functions small and focused on one task.
โ
Use type hints for readability.
Example with Type Hints:
def divide(a: int, b: int) -> float:
"""Returns division of two numbers"""
return a / b
Code reusability โ Write once, use many times.
Modularity โ Organize code into logical blocks.
Readability โ Easier to understand and maintain.
Debugging โ Simplifies error detection.
Defining functions in Python is essential for writing clean, modular, and reusable code. Whether youโre working with built-in, user-defined, or lambda functions, mastering them will help you build efficient and maintainable Python applications.