Functions are one of the most important building blocks in Python. They help you organize your code, avoid repetition, and improve readability. Whether you're automating tasks, processing data, or building complex applications, functions make your code modular and reusable.
In this guide, you’ll learn what functions are, how to define and use them, and the different types of functions with plenty of examples to build a strong foundation.
1. What is a Function in Python?
A function is a named block of code that performs a specific task. You define it once and call it whenever you need it. Functions can accept input (parameters), perform actions, and return results.
2. Defining a Function
Use the def
keyword to define a function. Function names should be descriptive and follow lowercase_with_underscores style.
# Example 1: Basic function
def greet():
print("Hello, welcome to Python!")
greet() # Output: Hello, welcome to Python!
3. Function with Parameters
You can pass information to a function using parameters. These values are accessible inside the function and can be used in operations.
# Example 2: Function with parameters
def greet_user(name):
print(f"Hello, {name}!")
greet_user("Rahul") # Output: Hello, Rahul!
4. Returning Values from a Function
Functions can return values using the return
keyword. This is useful when you want to capture and reuse the result.
# Example 3: Function that returns a value
def add(a, b):
return a + b
result = add(5, 7)
print(result) # Output: 12
5. Function with Default Parameters
You can provide default values for parameters. If a value is not provided when the function is called, the default is used.
# Example 4: Function with default argument
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Output: Hello, Guest!
greet("Ananya") # Output: Hello, Ananya!
6. Function with Multiple Return Values
Functions can return multiple values as a tuple.
# Example 5: Multiple return values
def get_stats(numbers):
return min(numbers), max(numbers)
low, high = get_stats([3, 5, 2, 8])
print(f"Min: {low}, Max: {high}")
7. The Importance of Function Naming
Use clear and descriptive names for functions. For example, calculate_total()
is better than ct()
.
8. Reusability and Modularity
Functions allow you to reuse code instead of writing it repeatedly. This makes your code cleaner and easier to debug.
# Example 6: Reusable function
def square(x):
return x * x
print(square(3)) # Output: 9
print(square(5)) # Output: 25
9. Function Best Practices
- Keep functions short and focused on a single task.
- Use parameters and return values effectively.
- Write a short comment or use a docstring to explain what the function does.
# Example 7: Function with a docstring
def multiply(x, y):
"""Multiply two numbers and return the result."""
return x * y
10. Anonymous Functions (lambda)
Python also supports small, anonymous functions using the lambda
keyword. These are typically used for short operations.
# Example 8: Lambda function
square = lambda x: x * x
print(square(6)) # Output: 36
11. Built-in vs User-defined Functions
- Built-in functions are provided by Python, like
len()
,sum()
,type()
. - User-defined functions are created by you using
def
.
Summary
- Functions help break your code into manageable, reusable parts.
- Use
def
to define a function andreturn
to send results back. - Functions can take parameters, return values, and even return multiple results.
- Use descriptive names and keep functions focused on a single task.
Final Thoughts
Functions are the heart of any Python program. Mastering them will make your code cleaner, easier to understand, and far more efficient. As your projects grow, you'll find functions invaluable for maintaining and scaling your codebase.