Skip to content

How to Compute the Average of Two Numbers in Python

Learn how to calculate the average of two numbers in Python using arithmetic operations, the statistics module, and input validation techniques.

Calculating the average (mean) is one of the most fundamental operations in programming, serving as a building block for statistical analysis, data normalization, and algorithm logic. In Python, computing the average of two numbers is straightforward, but it requires an understanding of operator precedence and data types to ensure accuracy.

This guide explores the standard arithmetic approach, how to handle inputs dynamically using built-in functions, and how to use the standard statistics library for more robust calculations.

Method 1: The Arithmetic Approach (Standard)

The mathematical definition of an average for two numbers is the sum of the numbers divided by the count (which is 2).

Average = (a + b) / 2

In Python, it is critical to use parentheses to control the order of operations. Division / has higher precedence than addition +.

num1 = 10
num2 = 20

wrong_average = num1 + num2 / 2
print(f"Wrong Result: {wrong_average}")

correct_average = (num1 + num2) / 2
print(f"Correct Result: {correct_average}")

Output:

Wrong Result: 20.0
Correct Result: 15.0

Method 2: Using the statistics Module

Python includes a built-in module called statistics which handles mean calculations. This is preferred when dealing with lists or when you want to make your intent explicitly clear.

import statistics

num1 = 5.5
num2 = 4.5

average_val = statistics.mean([num1, num2])

print(f"Average: {average_val}")

Output:

Average: 5.0

Method 3: Handling Input Errors

A common runtime error occurs when trying to calculate the average of user inputs without converting data types. Inputs usually come as strings.

def calculate_safe_average(a, b):
    try:
        
        val1 = float(a)
        val2 = float(b)
        return (val1 + val2) / 2
    except ValueError:
        return "Error: Inputs must be numeric."

print(calculate_safe_average(10, 20))
print(calculate_safe_average("10", "50")) # String inputs
print(calculate_safe_average("ten", 20))  # Invalid input

Output:

15.0
30.0
Error: Inputs must be numeric.

Advanced: Integer Optimization with Bitwise Operators

For integers only, you can calculate the average using the bitwise right shift operator >>. Shifting bits to the right by 1 is computationally equivalent to integer division by 2 (// 2).

a = 100
b = 50

avg_bitwise = (a + b) >> 1

print(f"Bitwise Average: {avg_bitwise}")

Output:

Bitwise Average: 75

Conclusion

To compute the average of two numbers in Python:

  1. Use (a + b) / 2 for standard calculations, ensuring you use parentheses.
  2. Use statistics.mean([a, b]) for readability or when dealing with lists.
  3. Validate inputs to ensure you are performing math on numbers, not strings.
Navigation