Skip to main content

How to Compute the Average of Two Numbers in Python

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

# ⛔️ Incorrect: Division happens first due to precedence
# Logic: 10 + (20 / 2) = 10 + 10 = 20
wrong_average = num1 + num2 / 2
print(f"Wrong Result: {wrong_average}")

# ✅ Correct: Parentheses force addition first
# Logic: (10 + 20) / 2 = 30 / 2 = 15.0
correct_average = (num1 + num2) / 2
print(f"Correct Result: {correct_average}")

Output:

Wrong Result: 20.0
Correct Result: 15.0
note

Python's standard division operator / always returns a float (e.g., 15.0), even if the result is a whole number. If you strictly need an integer result (flooring), use the floor division operator //.

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

# ✅ Correct: Passing values as a list or tuple
# This handles float precision and list lengths automatically
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:
# ⛔️ Incorrect: Adding strings concatenates them ("10" + "20" = "1020")
# Then dividing a string by an integer raises a TypeError

# ✅ Correct: Ensure inputs are numbers
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

# ✅ Correct: Fast integer averaging
# (100 + 50) >> 1 is equivalent to 150 // 2
avg_bitwise = (a + b) >> 1

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

Output:

Bitwise Average: 75
warning

This method works only for integers. If you apply it to floats (10.5 >> 1), Python raises a TypeError. Additionally, it performs floor division, meaning (5 + 2) >> 1 results in 3 (from 3.5), which loses precision.

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.