0

I'm practicing previous python exam question for an upcoming exam but my code is screwy.

  1. The task is to make a text file with a list of weights in grams (done).

  2. Prompts user for file name, reads the weights, adds them in a list and calculates the total weight.

Herein lies the problem:

try:

   file = input('Enter file name:')

   f = open('weights.txt', 'r')

   sum=0

   for line in f:

      sum = sum+(int(line.strip()))/1000

      print('The textbook weight in kg:', sum)

except:

   print('File cannot be opened')

The output the programme shows is:

"The textbook weight in kg: 0.5

The textbook weight in kg: 0.65

The textbook weight in kg: 1.35

The textbook weight in kg: 1.6500000000000001

The textbook weight in kg: 1.9000000000000001"

But the output i need is:

1.9 only,without the previous lines.

As I'm still a beginner, I know very little about the correct code. So any help will be appreciated

  • Can you elaborate on what exactly is the issue? Or the _expected_ output? – dmitriys Nov 13 '18 at 00:21
  • The expected output is 1.9kg –  Nov 13 '18 at 00:22
  • This is just floating point inaccuracy, you just need to round the numbers to something more appropriate (such as to two decimal places). You can do this by `round(output, 2)` – Polymer Nov 13 '18 at 00:25
  • For clarification, floating point inaccuracy is explained here http://effbot.org/pyfaq/why-are-floating-point-calculations-so-inaccurate.htm – Polymer Nov 13 '18 at 00:26
  • There is this very non beginner friendly answer https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Paul Rooney Nov 13 '18 at 00:27
  • btw, it's python3 code so please don't add python-2.7 in tags – Kevin Fang Nov 13 '18 at 00:30

1 Answers1

4

Your problem is with your indentation. You should print your result after the whole for loop is executed, i.e.

try:
    file = input('Enter file name:')
    f = open('weights.txt', 'r')
    sum=0   
    for line in f:
        sum = sum+(int(line.strip()))/1000
    print('The textbook weight in kg:', sum)
except:
    print('File cannot be opened')

Also for the floating point inaccuracy thing, you could format your print like this:

print('The textbook weight in kg:{:.2f}'.format(sum))
# The textbook weight in kg:1.90
Kevin Fang
  • 1,966
  • 2
  • 16
  • 31
  • Can you explain the format so that I can remember and understand when to apply? –  Nov 13 '18 at 00:46
  • @topu `{}` marks the position you want to replace with the argument of `format`, `:` means the argument is to be formatted, `.2f` means floating point with 2 digits precision. For mor usage please refer to some tutorial website such as https://pyformat.info/ – Kevin Fang Nov 13 '18 at 01:21
  • P.S. next time don't use question title like this, see https://stackoverflow.com/help/how-to-ask – Kevin Fang Nov 13 '18 at 01:23