# Coding Practice: Calculating the Average of a List of Numbers

Try the following code

# Introduction

# Coding practice is essential for improving your programming skills. In this example, we will walk through a Python program to calculate the average of a list of numbers. We'll emphasize good coding practices such as clear variable names, comments, and modular code.


# Define the List

# Let's start by defining a list of numbers. You can modify this list to include any set of numbers you want to find the average of.


numbers = [45, 67, 89, 12, 34, 56, 78, 90]


# Initialize Variables

# To calculate the average, we need to sum all the numbers in the list and then divide by the count of numbers. We'll initialize variables to keep track of these values.


total_sum = 0  # To store the sum of numbers

count = 0      # To count the number of elements in the list


# Calculate the Sum

# We'll loop through the list, add each number to the total_sum, and increment the count for each element.


for num in numbers:

    total_sum += num  # Add the current number to the sum

    count += 1        # Increment the count


# Calculate the Average

# After summing all the numbers and counting them, we can calculate the average by dividing the total_sum by the count.


average = total_sum / count


# Display the Result

# Finally, we'll display the calculated average to the user.


print(f"The average of the numbers is: {average}")


# Summary

# This Python program demonstrates good coding practices, including clear variable names, comments for explaining code sections, and modular code structure. Coding practice helps you develop problem-solving skills and write more readable and maintainable code.


# Function Approach (Modular Code)

# Let's take this a step further by encapsulating the average calculation in a function. This modular approach enhances code reusability and readability.


def calculate_average(number_list):

    """

    Calculates the average of a list of numbers.

    

    Args:

        number_list (list): A list of numeric values.

    

    Returns:

        float: The average of the numbers.

    """

    total_sum = 0

    count = 0

    

    for num in number_list:

        total_sum += num

        count += 1

    

    average = total_sum / count

    return average


# Now, we can use this function to calculate the average of any list of numbers.


# Example 1

numbers1 = [22, 33, 44, 55, 66]

result1 = calculate_average(numbers1)

print(f"Average of numbers1: {result1}")


# Example 2

numbers2 = [15, 25, 35, 45, 55, 65, 75, 85, 95]

result2 = calculate_average(numbers2)

print(f"Average of numbers2: {result2}")


# Summary

# By encapsulating the average calculation in a function, we've made our code more modular and reusable. This approach is beneficial when you need to calculate averages multiple times with different sets of numbers.


# Error Handling

# In real-world scenarios, you may encounter situations where the input data is not as expected. It's essential to handle such cases gracefully. Let's add error handling to our code.


def calculate_average_with_error_handling(number_list):

    """

    Calculates the average of a list of numbers.

    

    Args:

        number_list (list): A list of numeric values.

    

    Returns:

        float: The average of the numbers.

        None: Returns None if the input list is empty.

    """

    total_sum = 0

    count = 0

    

    if not number_list:  # Check if the list is empty

        return None

    

    for num in number_list:

        total_sum += num

        count += 1

    

    average = total_sum / count

    return average


# Error Handling Example

empty_list = []  # An empty list

result_empty = calculate_average_with_error_handling(empty_list)


if result_empty is None:

    print("The input list is empty. Cannot calculate average.")

else:

    print(f"Average of empty_list: {result_empty}")


# Summary

# Error handling is a crucial aspect of coding practice. It ensures that your code can gracefully handle unexpected situations, such as empty input data, and provides informative feedback to users.


# Conclusion

# This example has highlighted important coding practices such as clear variable names, comments, and modular code structure. We've also explored error handling to handle unexpected scenarios gracefully. By following these practices, you can write clean, readable, and robust code. Coding practice is a journey of continuous improvement, so keep coding and learning!