Reputation:
I'm practicing previous python exam question for an upcoming exam but my code is screwy.
The task is to make a text file with a list of weights in grams (done).
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
Upvotes: 0
Views: 132
Reputation: 2012
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
Upvotes: 4