Using the data provided, generate a report of a player's batting average and slugging percentage by month. Use Python to perform the following tasks:

1. Calculate the batting average (BA) for each month using the formula: \[ BA = \frac{\text{hits}}{\text{at bats}} \]

2. Calculate the slugging percentage for each month using the formula: \[ \text{Slugging Percentage} = \frac{\text{total bases}}{\text{at bats}} \]

3. Print out each month along with the number of hits, number of at bats, batting average, and slugging percentage.

The input data is organized as follows for each month:
- Month
- Plate Appearances
- At Bats
- Runs
- Hits
- Total Bases

Example Data:
- April: 107 plate appearances, 90 at bats, 29 runs, 31 hits, 66 total bases, 0.344 BA
- May: 106 plate appearances, 94 at bats, 23 runs, 35 hits, 72 total bases, 0.372 BA
- June: 77 plate appearances, 62 at bats, 12 runs, 18 hits, 29 total bases, 0.29 BA
- July: 115 plate appearances, 103 at bats, 20 runs, 34 hits, 59 total bases, 0.33 BA
- August: 124 plate appearances, 102 at bats, 25 runs, 36 hits, 63 total bases, 0.353 BA
- September: 85 plate appearances, 69 at bats, 20 runs, 26 hits, 44 total bases, 0.377 BA

Note: Ensure your Python script reads from a file named "stats.txt" organized in the same format as above.

Answer :

Answer:

Check the explanation

Explanation:

with open('stats. txt', 'r') as # open the file in read mode

list1 = [] # initialize an empty list

for i in . readlines (): # read every line of file

for j in i. split (): # split each line by a space and append it to the list1

list1. append (j)

months = [] # initialize required lists to empty list

plate_apperence = []

at_bats = []

runs = []

hits = []

total_bats = []

for i in range(0, len(list1)-1, 7): # use a for loop and give parameters as start,stop and step count

months. append(list1[i]) # append list1 elements to required lists

plate_apperence. append(int(list1[i+1]))

at_bats. append(int(list1[i+2]))

runs. append(int(list1[i+3]))

hits. append(int(list1[i+4]))

total_bats. append(int(list1[i+5]))

for i in range(len(months)): # for each element in months

print("Player's Average Batting and slugging percent for the month ", months[i], " is as shown below")

print("{:.2f}".format(hits[i]/at_bats[i])) # calculate Average batting and slugging percent and print them

print("{:.2f}". format(total_bats[i]/at_bats[i]))

print("\n")

Kindly check the attached images below to get the Code Screenshot and Code Output.