139k views
16 votes
The steps.txt file contains the number of steps a person has taken each day for a year. There are 365 lines in the file, and each line contains the number of steps taken during a day. (The first line is the number of steps taken on January 1st, the second line is the number of steps taken on January 2nd, and so forth.) Write a program that reads the file, then displays the average number of steps taken for each month. (The data is from a year that was not a leap year, so February has 28 days.)

User Andynu
by
7.4k points

1 Answer

2 votes

Answer:

In Python:

file = open('steps.txt', 'r')

readLine = file.readlines()

begin = 0

mdays = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

print("Month"+"\t\t"+"Average Steps")

for m in range(len(mdays)):

end = begin + mdays[m]

steps = readLine[begin:end]

sumsteps = 0

for s in steps:

sumsteps = sumsteps + int(s)

average = round(sumsteps/mdays[m],1)

print(str(m+1)+"\t\t"+str(average))

begin = begin + mdays[m]

Step-by-step explanation:

This line opens the step.txt file

file = open('steps.txt', 'r')

This reads the content of the file

readLine = file.readlines()

begin = 0

This initializes the months of the days to a tuple

Mmdays = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

This prints the header

print("Month"+"\t\t"+"Average Steps")

This iterates through the tuple

for m in range(len(Mmdays)):

This calculates the days in each month

end = begin + Mmdays[m]

This gets the number of steps in each month

steps = readLine[begin:end]

This initializes the number of steps to 0

sumsteps = 0

This iteration sums up the number of steps in each month

for s in steps:

sumsteps = sumsteps + int(s)

This calculates the average of steps rounded to 1 decimal place

average = round(sumsteps/Mmdays[m],1)

This prints the calculated average

print(str(m+1)+"\t\t"+str(average))

This calculates the beginning of the new month

begin = begin + Mmdays[m]

User Joydeep
by
7.1k points