May-07-2018, 09:40 AM
(This post was last modified: May-07-2018, 09:40 AM by toxicxarrow.)
This assignment is technically complete according to my instructions, but I would like to polish it up a bit for my own learning experience. Basically, I was tasked to display 15 numbers in a file, then calculate the average of said numbers.
In this line of code:
Question 2: What can I add to ignore spaces in the file, and only use the numbers on each line? The code works fine if the numbers are in a nice column without any spaces; however, I get an error if there is a single space in between the numbers.
Please keep any suggestions as close to the initial code as possible, and thank you for reading this far.
Cheers.
# Initialize constants
total = 0
lines = 0
file = 0
average = 0
# Gather all numbers in file for display
with open('numbers.dat', 'r') as file:
lines = file.read()
# Add all numbers in file
for add in open('numbers.dat'):
total += int(add.strip())
# Calculate the average of numbers in file
average = total / 15
average = round(average, 2)
#Print all numbers in file
print('The numbers in the file are:')
print(lines)
# Print the average of numbers in file
print('The average of those numbers is:')
print(average)
# Close file
file.close()
# END #Question 1:In this line of code:
# Calculate the average of numbers in file average = total / 15 average = round(average, 2)How can I replace the "15" with the number of integers that are actually in the file? Say I wanted to put 20 numbers in there instead of 15 to calculate the average, I'd like the total to be divided by the amount of numbers there are, not just a constant.
Question 2: What can I add to ignore spaces in the file, and only use the numbers on each line? The code works fine if the numbers are in a nice column without any spaces; however, I get an error if there is a single space in between the numbers.
Please keep any suggestions as close to the initial code as possible, and thank you for reading this far.
Cheers.
