Functions in Python: Why and How to Use Them Efficiently

This article is a complementary resource to the Learn Python Basics course.

Functions in Python: Why and How to Use Them Efficiently

A Python function is a block of code designed to perform a specific task. For example:

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

Here, greet() is a function that prints a greeting message. To use this function in your code, you simply need to call it:

greet("Mufasa")
greet("Moana")

Each time you call greet() with a different name, it will print a personalized greeting.

As you know, functions can have arguments, return values, or neither. As a beginner, it can be tricky to decide which type of function to use.

Let's explore different ways to write a function for calculating the sum of natural numbers and see how adding arguments and return values makes the function more flexible.


Example 1: Function Without Arguments or Return Value

Let's start by finding the sum of the first 10 natural numbers using a simple function:

def sum_of_natural_numbers():
    total = 0
    n = 10
    for i in range(n):
        total += i
    print(f"The sum is {total}.")
    
# Call the function
sum_of_natural_numbers()

You can use this function as it is, but it limits you to calculating the sum of the first 10 natural numbers.

If you want to find the sum of, say, the first 11 natural numbers, you'd need to modify the function or create a new one.

While this works for the current task, it lacks flexibility and reusability.


Example 2: Function with Arguments

If you want your function to calculate the sum of any number of natural numbers, you can use arguments to make it more flexible.

# Function with arguments
def sum_of_natural_numbers(n):
    total = 0
    for i in range(n):
        total += i
    print(f"The sum is {total}.")
    
# Call the function
sum_of_natural_numbers(10)
sum_of_natural_numbers(20)

By using arguments, you avoid hardcoding values. Now, the function can calculate the sum for any number of natural numbers you pass in, making it more reusable and adaptable to different inputs.

This works well.

But what if you need to add 5 to the total value after calling the function?

With a return value, you can store the result and directly perform further calculations, like adding 5 to it.


Example 3: Function with Both Argument and Return Values

# Function with arguments and return value
def sum_of_natural_numbers(n):
    total = 0
    for i in range(n):
        total += i
    return total
    
# Call the function and store the result
sum_result = sum_of_natural_numbers(10)

# Now you can use this value in any operation
sum_result_plus_5 = sum_result + 5
print(f"The sum plus 5 is: {sum_result_plus_5}")

We explored different approaches to writing a function for calculating the sum of natural numbers, each with its advantages and limitations.

For finding the sum of natural numbers, using both arguments and return values was the best option, as it offered the most flexibility.

However, the optimal approach always depends on the specific task your function needs to accomplish.


Best Practices for Functions

While using arguments and return values is generally the best approach, there are cases where simpler functions are more appropriate.

For example, if the function's only job is to perform an action, such as printing or modifying variables, you do not need a return value.

def display_message(user):
    print(f"Hello {user}")

Similarly, if the function performs a predefined task that doesn't rely on input, you can omit arguments.

def show_greeting():
    print("Welcome!")

Or, as seen above, you can omit both arguments and return values.


When to Use Which Type of Function

Question Yes No
Does the function need to work with different input values? Use a parameterized function Use a function without parameters
Does the function's result need to be reused or stored? Use a function with a return value Use a function without a return value