Functions are the building blocks of clean, reusable, and organized code. In Python, we define functions using the def keyword. Whether you're automating tasks, building machine learning models, or just writing cleaner scripts, understanding how to define and use functions is essential.
A function is a named block of code that performs a specific task. You can call it whenever you need it, instead of rewriting the same logic multiple times.
Reusability: Write once, use many times.
Modularity: Break your code into manageable chunks.
Readability: Make your code easier to understand.
Maintainability: Easier to debug and update.
def function_name(parameters):
"""Optional docstring explaining the function."""
# Code block
return result
def greet(name):
"""Greets the user by name."""
return f"Hello, {name}!"
Calling the function:
print(greet("Wahab"))
# Output: Hello, Wahab!
Parameters are variables listed inside the parentheses in the function definition.
Arguments are the actual values passed to the function when calling it.
You can define functions with:
No parameters
One or more parameters
Default values
Variable-length arguments (*args, **kwargs)
def greet(name="Guest"):
return f"Hello, {name}!"
print(greet()) # Output: Hello, Guest!
print(greet("Wahab")) # Output: Hello, Wahab!
The return keyword sends back the result of the function to the caller.
def add(a, b):
return a + b
If you don’t use return, the function returns None by default.
Use triple quotes """ to describe what your function does. This helps others (and your future self) understand your code.
def square(n):
"""Returns the square of a number."""
return n ** 2
You can access the docstring using:
print(square.__doc__)
Use descriptive function names.
Keep functions focused on a single task.
Write docstrings for clarity.
Avoid global variables inside functions.
Here’s a simple challenge:
Write a function called is_even that takes a number and returns True if it’s even, otherwise False.
def is_even(n):
return n % 2 == 0
Functions are a core concept in Python and mastering them will make your code cleaner, smarter, and more efficient. As you move forward into data science and machine learning, functions will help you structure your projects and reuse logic effectively.
Next Up: Parameters and return values