我的程序运行但它只输出" MONTH | AVERAGE&#34 ;.我需要它来发布每个月采取的步骤。
days = [31,28,31,30,31,30,31,31,30,31,30,31]
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
firstIndex = 0
lastIndex = 0
inputFile = open(r'C\Users\UserName\Downloads\steps.txt', 'r')
outputFile = open(r'C\Users\UserName\Downloads\stepsbymonth.txt', 'w')
outputFile.write('MONTH | AVERAGE\n')
print('MONTH | AVERAGE\n')
lines = inputFile.readlines()
lines = list(map(int,lines))
for x in range(0, 12):
lastIndex = firstIndex + days[x]
monthLines = lines[firstIndex:lastIndex]
average = float(sum(monthLines)) / max(len(monthLines),1)
outputFile.write(months[x] + '|' + '{0:.1f}'.format(average)+ '\n')
firstIndex = lastIndex
inputFile.close()
outputFile.close()
答案 0 :(得分:0)
你不是print
号码。
另外,请使用outputFile = open(r'C\Users\UserName\Downloads\stepsbymonth.txt', 'a'
,因为您不想覆盖该文件。
答案 1 :(得分:0)
# Global Variables/Constants
month = ('January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December')
days = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
# Main Module
def main():
# This calls the welcome module
welcome()
# This calls the Step Tracker module
stepTracker()
# Welcome Module
def welcome():
print ('Here is your workout information for the year:')
print ('__________________________________________________________________')
print ('')
# Counter Module
def stepTracker():
# This opens the steps.txt file
stepCounter = open('steps.txt', 'r')
# This sets the month count to zero which begins the tuple.
monthCount = 0
# This loops through the months until the 12th month is reached
for num in range(1, 13):
# This resets the base values for the counters on each months iteration
totalSteps = 0
count = 0
average = 0
# This iterates until the end of the month is reached
for count in range(1, days[monthCount] + 1):
# This reads the lines until the end of the month is reached
steps = int(stepCounter.readline())
# This sums the months
totalSteps = totalSteps + steps
# This averages the steps for the month
average = totalSteps / days[monthCount]
# This prints the average for the month
print ('The average steps taken for the month of ' + month[monthCount] +
' is: ' + format(average, ',.1f') + ' steps.')
# This increments the months count
monthCount = monthCount + 1
# This calls the main module
main()