I am currently working on a python program that takes the numbers from a large file and averages them. Currently I can't seem to find a way to add the numbers without using the sum function. I am a beginner and am just trying to grasp the basics of Python so this is a little tricky for me. I have been working on the code for days now and can't seem to find a solution any suggestions?

Dani AI

Generated

As and noted, seeing the current code helps diagnose the exact problem. Meanwhile, a simple, robust pattern for reading numbers from a text file and summing them manually is shown below. The approach streams the file (constant memory), converts tokens to numbers with error handling, keeps a running total and count, then computes the average without using sum().

total = 0.0
count = 0

with open('numbers.txt', 'r', encoding='utf-8') as f:
    for line in f:
        line = line.strip()
        if not line:
            continue
        # If a line can contain multiple numbers, split it; otherwise skip the split.
        for token in line.split():
            try:
                num = float(token)
            except ValueError:
                # skip non-numeric tokens (or log them)
                continue
            total += num
            count += 1

if count:
    average = total / count
    print('Count:', count, 'Sum:', total, 'Average:', average)
else:
    print('No numeric data found.')

Notes and troubleshooting tips:

  • If every line contains exactly one integer, replace float(token) with int(line) and remove the inner split() loop for simplicity.
  • For comma-separated values use for token in line.replace(',', ' ').split(): or the csv module for robust parsing.
  • For large files this streaming approach avoids loading everything into memory. For high-precision or financial sums, use decimal.Decimal or a compensated summation (Kahan) to reduce floating-point error. A simple Kahan loop replaces total += num with a compensated update when needed.

Recommended Answers

All 2 Replies

So what have you got so far? Show us the code

Yes, please show us the code you already have so we can see where it is that you're stuck. Is this a homework assignment that doesn't allow you to use the sum function?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.