Question

Chapter 8 Python Case study Baseball Team Manager

For this case study, you’ll use the programming skills that you learn in Murach’s Python Programming to develop a program that helps a person manage a baseball team. This program stores the data for each player on the team, and it also lets the manager set a starting lineup for each game. After you read chapter 2, you can develop a simple program that calculates the batting average for a player. Then, after you complete most of the other chapters, you can enhance and improve this program.

***PLEASE I NEED THIS ASAP, ITS DUE MONDAY 07/08

Chapter 08: Handle exceptions

Thoroughly test the program and update it so it handles all exceptions that you encounter during testing.

******This is what the Professor had provided us and this screenshot is what the assignment should look like in IDLE.

Baseball Team Manager MENU OPTIONS 1 Display lineup 2 Add player 3 Remove player 4 Move player 5 Edit player position 6 Edit

Specifications

- Handle the exception that occurs if the program can’t find the data file.

- Handle the exceptions that occur if the user enters a string where an integer is expected.

- Handle the exception that occurs if the user enters zero for the number of at bats.

Here is what I currently have from previous assignments:

import csv

def readData():
players = []
with open('bball.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
players.append(row)
return players
  
def saveData(players):
with open('bball.csv', 'w',newline='') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerows(players)
  
players=[['joe','P',10,2,0.2],['Tom','SS',11,4,0.364],['Ben','3B',0,0,0.0]] # creating an list of lists with few playes information
position=('C','1B','2B','3B','SS','LF','CF','RF','P') # creating a tuple for storing valid positions

choice=0 # choice variable for taking user's menu choice
lineup=1 # lineup to take the lineup number from user
flag=0 # used to check whether the position entered is valid or not
numOfPlayers=3 # to keep hold on the number of players

print("MENU OPTIONS") # display the menu
print("1-Display lineup")
print("2-Add player")
print("3-Remove Player")
print("4-Move player")
print("5-Edit player position")
print("6-Edit player stats")
print("7-Exit program")

while choice!=7: # loop till the choice of user is not equal to 7

choice=int(input("Menu Option:")) # take user's menu option in variable choice

if choice==1: # if choice is 1
lineup=1
for player in players: # loop through the list and display each players' information
print(str(lineup),end=' ')
for item in player:
print(str(item),end=' ')
lineup=lineup+1
print()
  

elif choice==2: # if the user's choice is 2
name=input("Name:") # take name and position from user
pos=input("Position")
flag=0
while flag==0: # if user is provided valid position
for item in position: # set flag to 1 and come out of loop
if item==pos: # else keep on looping till valid position is provided
flag=1
if flag==0:
print("Incorrect position")
pos=input("Position:")
AB=int(input("At bats:")) # take at bats and hits value from user
hit=int(input("Hits:"))

if AB!=0: # if at bats is not 0, set avg as hits / at bats
avg=float(hit)/float(AB) # else set avg as 0

else:
avg=0
NewPlayer=[name,pos,AB,hit,avg] # create a list as newPlayer, and update the list with new info
players.append(NewPlayer) # append the list newplayer to players list
numOfPlayers=numOfPlayers+1 # increment number of players by 1

elif choice==3: # if choice is 3
lineup=int(input("lineup number:")) # take lineup number from user
while lineup>numOfPlayers: # if lineup number is greater than number of player
print("Please enter the correct lineup number:") # then show appropriate info and again ask for lineup number
lineup=int(input("lineup number:")) # display the player's information with specified lineup
print("You selected " + str(players[lineup-1][0]) + " "+ str(players[lineup-1][1]) +" "+ str(players[lineup-1][2]) +" "+ str(players[lineup-1][3]) +" "+ str(players[lineup-1][4]))
del players[lineup-1] # delete the player with specified lineup
numOfPlayers=numOfPlayers-1 # decrement num of players by 1
print("The player with lineup number " + str(lineup) + " has been removed")

elif choice==4: # if choice is 4
current_lineup=int(input("Current lineup number:")) # take current lineup from user and print the player's info
print("You selected " + str(players[current_lineup-1][0]))

new_lineup=int(input("New lineup number:")) # take new lineup from user
i=0
while i<5: # swap all the data between the given lineups
temp=players[current_lineup-1][i]
players[current_lineup-1][i]=players[new_lineup-1][i]
players[new_lineup-1][i]=temp
i=i+1
print(str(players[new_lineup-1][0]) + " was moved")

elif choice==5: # if choice is 5
lineup=int(input("lineup number:")) # take line up from user
while lineup>numOfPlayers: # show appropriate message and again ask for lineup if incorrect
print("Please enter the correct lineup number:") # lineup is provided
lineup=int(input("lineup number:"))
print("You selected " + str(players[lineup-1][0]) + " Pos=" + str(players[lineup-1][1])) # show player's information


pos=input("Position:") # Ask the position to change
flag=0
while flag==0: # get appropriate position, if incorrect position is specified
for item in position:
if item==pos:
flag=1
if flag==0:
print("Incorrect position")
pos=input("Position:")

players[lineup-1][1]=pos # update the player's information with new position
print(str(players[lineup-1][0]) + " updated")

elif choice==6: # if choice is 6
lineup=int(input("lineup number:")) # take correct lineup number from user
while lineup>numOfPlayers:
print("Please enter the correct lineup number:")
lineup=int(input("lineup number:"))

print("You selected " + str(players[lineup-1][0]) + " AB=" + str(players[lineup-1][2]) + " hits=" + str(players[lineup-1][3]))
AB=int(input("At bats:")) # take the value of at bats and hits from user
hit=int(input("Hits:"))

players[lineup-1][2]=AB # update the player's information with new at bats and hots
players[lineup-1][3]=hit
if AB==0: # also calculate average and update
players[lineup-1][4]=0
else:
players[lineup-1][4]=float(hit)/float(AB)

print(str(players[lineup-1][0]) + " updated")

elif choice==7: # if choice is 7, print break and come out of the loop
print("Au revoir!")

0 0
Add a comment Improve this question Transcribed image text
Answer #1

'''

Python program to create a baseball management system

'''

import csv

def readData():

               players = []

               try:

                              with open('bball.csv', 'r') as csvfile:

                                             csvreader = csv.reader(csvfile)

                                             for row in csvreader:

                                                            players.append(row)

                                             return players

               except IOError:

                              print('Team data file could not be found.\nYou can create a new one if you want.')

def saveData(players):

               try:

                              with open('bball.csv', 'w',newline='') as csvfile:

                                             csvwriter = csv.writer(csvfile)

                                             csvwriter.writerows(players)                      

               except IOError:

                              print('Team data file could not be found.\nYou can create a new one if you want.')

                             

players=[['joe','P',10,2,0.2],['Tom','SS',11,4,0.364],['Ben','3B',0,0,0.0]] # creating an list of lists with few playes information

position=('C','1B','2B','3B','SS','LF','CF','RF','P') # creating a tuple for storing valid positions

choice=0 # choice variable for taking user's menu choice

lineup=1 # lineup to take the lineup number from user

flag=0 # used to check whether the position entered is valid or not

numOfPlayers=3 # to keep hold on the number of players

print("="*64)

print("\t\tBaseball Team Manager")

print("MENU OPTIONS") # display the menu

print("1-Display lineup")

print("2-Add player")

print("3-Remove Player")

print("4-Move player")

print("5-Edit player position")

print("6-Edit player stats")

print("7-Exit program")

# display the positions

print("\nPOSITIONS:")

for x in position:

               print((x),end=",")                             

print("\n")           

# call the method to read the data from the csv file

readData()          

print("="*64)

while choice!=7: # loop till the choice of user is not equal to 7                      

               try:

                              choice=int(input("\nMenu Option:")) # take user's menu option in variable choice

                              if choice==1: # if choice is 1

                                             lineup=1

                                             for player in players: # loop through the list and display each players' information

                                                            print(str(lineup),end=' ')

                                                            for item in player:

                                                                           print(str(item),end=' ')

                                                            lineup=lineup+1

                                                            print()

                                                           

                              elif choice==2: # if the user's choice is 2

                                             name=input("Name: ") # take name and position from user

                                             pos=input("Position: ")

                                             flag=0                  

                                             while flag==0: # if user is provided valid position

                                                            for item in position: # set flag to 1 and come out of loop

                                                                           if item==pos: # else keep on looping till valid position is provided

                                                                                          flag=1

                                                            if flag==0:

                                                                           print("Incorrect position")

                                                                           pos=input("Position:")

                                             AB=int(input("At bats: ")) # take at bats and hits value from user

                                             hit=int(input("Hits: "))                    

                                             if AB!=0: # if at bats is not 0, set avg as hits / at bats

                                                            avg=float(hit)/float(AB) # else set avg as 0

                                             else:

                                                            avg=0

                                             NewPlayer=[name,pos,AB,hit,avg] # create a list as newPlayer, and update the list with new info

                                             players.append(NewPlayer) # append the list newplayer to players list

                                             numOfPlayers=numOfPlayers+1 # increment number of players by 1

                                             print(name+' was added')

                             

                              elif choice==3: # if choice is 3

                                             lineup=int(input("lineup number:")) # take lineup number from user

                                             while lineup>numOfPlayers: # if lineup number is greater than number of player

                                                            print("Please enter the correct lineup number:") # then show appropriate info and again ask for lineup number

                                                            lineup=int(input("lineup number:")) # display the player's information with specified lineup

                                             print("You selected " + str(players[lineup-1][0]) + " "+ str(players[lineup-1][1]) +" "+ str(players[lineup-1][2]) +" "+ str(players[lineup-1][3]) +" "+ str(players[lineup-1][4]))

                                             del players[lineup-1] # delete the player with specified lineup

                                             numOfPlayers=numOfPlayers-1 # decrement num of players by 1

                                             print("The player with lineup number " + str(lineup) + " has been removed")

                             

                              elif choice==4: # if choice is 4

                                             current_lineup=int(input("Current lineup number:")) # take current lineup from user and print the player's info

                                             print("You selected " + str(players[current_lineup-1][0]))

                                             new_lineup=int(input("New lineup number:")) # take new lineup from user

                                             i=0

                                             while i<5: # swap all the data between the given lineups

                                                            temp=players[current_lineup-1][i]

                                                            players[current_lineup-1][i]=players[new_lineup-1][i]

                                                            players[new_lineup-1][i]=temp

                                                            i=i+1

                                             print(str(players[new_lineup-1][0]) + " was moved")

                              elif choice==5: # if choice is 5

                                             lineup=int(input("lineup number:")) # take line up from user

                                             while lineup>numOfPlayers: # show appropriate message and again ask for lineup if incorrect

                                                            print("Please enter the correct lineup number:") # lineup is provided

                                                            lineup=int(input("lineup number:"))

                                             print("You selected " + str(players[lineup-1][0]) + " Pos=" + str(players[lineup-1][1])) # show player's information

                                            

                                             pos=input("Position:") # Ask the position to change

                                             flag=0

                                             while flag==0: # get appropriate position, if incorrect position is specified

                                                            for item in position:

                                                                           if item==pos:

                                                                                          flag=1

                                                            if flag==0:

                                                                           print("Incorrect position")

                                                                           pos=input("Position:")

                                             players[lineup-1][1]=pos # update the player's information with new position

                                             print(str(players[lineup-1][0]) + " updated")

                                                           

                              elif choice==6: # if choice is 6

                                             lineup=int(input("lineup number:")) # take correct lineup number from user

                                             while lineup>numOfPlayers:

                                                            print("Please enter the correct lineup number:")

                                                            lineup=int(input("lineup number:"))

                                                           

                                             print("You selected " + str(players[lineup-1][0]) + " AB=" + str(players[lineup-1][2]) + " hits=" + str(players[lineup-1][3]))

                                             AB=int(input("At bats:")) # take the value of at bats and hits from user

                                             hit=int(input("Hits:"))

                                             players[lineup-1][2]=AB # update the player's information with new at bats and hots

                                             players[lineup-1][3]=hit

                                             if AB==0: # also calculate average and update

                                                            players[lineup-1][4]=0

                                             else:

                                                            players[lineup-1][4]=float(hit)/float(AB)

                                             print(str(players[lineup-1][0]) + " updated")

                                            

                              elif choice==7: # if choice is 7, print break and come out of the loop

                                             print("Au revoir!")

                                            

               except ValueError:

                              print('Not a valid option. Please try again')

                              print("\nMENU OPTIONS") # display the menu

                              print("1-Display lineup")

                              print("2-Add player")

                              print("3-Remove Player")

                              print("4-Move player")

                              print("5-Edit player position")

                              print("6-Edit player stats")

                              print("7-Exit program")

                             

#end of program                            

              

Code Screenshot:

Python program to create a baseball management system 4 import csv def readData () nlavers r try: with open (bball.csv, r

display the positions print (\nPoSITIONS:) for x in position: print (x),end-, ) print (\n) call the method to read thealif choice3: # if choice is 3 er: ) ) take lineup number from user while 1ineupnumof Pl ayers: # if lineup numher is greate106 elif 108 109 ineun-int (input (lineup number: ) ) take line up from user while lineup>numor Players: show appropriate m145 146 except ValueError: print (Not a valid option. Please try again) print (\nMENU OPTIONS) display the menu print (1

Output:

Baseball Team Manager MENU OPTIONS 1-Display lineup 2-Add player 8-Remove Player 4-Move player 5-Edit player position 5-Edit

Add a comment
Know the answer?
Add Answer to:
Chapter 8 Python Case study Baseball Team Manager For this case study, you’ll use the programming...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Case Study Baseball Team Manager. CMSC 135 Python Chapter 7 Assignment: Use a file to save...

    Case Study Baseball Team Manager. CMSC 135 Python Chapter 7 Assignment: Use a file to save the data Update the program so it reads the player data from a file when the program starts andwrites the player data to a file anytime the data is changed What needs to be updated: Specifications Use a CSV file to store the lineup. Store the functions for writing and reading the file of players in a separate module than the rest of the...

  • Something is preventing this python code from running properly. Can you please go through it and...

    Something is preventing this python code from running properly. Can you please go through it and improve it so it can work. The specifications are below the code. Thanks list1=[] list2=[] def add_player(): d={} name=input("Enter name of the player:") d["name"]=name position=input ("Enter a position:") if position in Pos: d["position"]=position at_bats=int(input("Enter AB:")) d["at_bats"] = at_bats hits= int(input("Enter H:")) d["hits"] = hits d["AVG"]= hits/at_bats list1.append(d) def display(): if len(list1)==0: print("{:15} {:8} {:8} {:8} {:8}".format("Player", "Pos", "AB", "H", "AVG")) print("ORIGINAL TEAM") for x...

  • Chapter 05 Case study Baseball team For this case study, you’ll use the programming skills that...

    Chapter 05 Case study Baseball team For this case study, you’ll use the programming skills that you learn in Murach’s Python Programming to develop a program that helps a person manage a baseball team. This program stores the data for each player on the team, and it also lets the manager set a starting lineup for each game. After you read chapter 2, you can develop a simple program that calculates the batting average for a player. Then, after you...

  • Question: Case Study Baseball Team Manager For this case study, you’ll use the programming skills that...

    Question: Case Study Baseball Team Manager For this case study, you’ll use the programming skills that you ... Case Study Baseball Team Manager For this case study, you'll use the programming skills that you learn in Murach s Python Programming to develop a program that helps a person manage a baseball team. This program stores the data for each player on the team, and it also lets the manager set a starting lineup for each game After you read chapter...

  • Week 10 Python programming Baseball Team Manager MENU OPTIONS 1 – Display lineup 2 – Add...

    Week 10 Python programming Baseball Team Manager MENU OPTIONS 1 – Display lineup 2 – Add player 3 – Remove player 4 – Move player 5 – Edit player position 6 – Edit player stats 7 - Exit program POSITIONS C, 1B, 2B, 3B, SS, LF, CF, RF, P Menu option: 1 POS AB H AVG Player 1 Denard Span CF 545 174 0.319 2 Brandon Belt 1B 533 127 0.238 3 Buster Posey C 535 176 0.329 4 Hunter...

  • Need help writing this code in python. This what I have so far. def display_menu(): print("======================================================================")...

    Need help writing this code in python. This what I have so far. def display_menu(): print("======================================================================") print(" Baseball Team Manager") print("MENU OPTIONS") print("1 - Calculate batting average") print("2 - Exit program") print("=====================================================================")    def convert_bat(): option = int(input("Menu option: ")) while option!=2: if option ==1: print("Calculate batting average...") num_at_bats = int(input("Enter official number of at bats: ")) num_hits = int(input("Enter number of hits: ")) average = num_hits/num_at_bats print("batting average: ", average) elif option !=1 and option !=2: print("Not a valid...

  • write a C# program using replit that uses a loop to input # at bats and # of hits for each of the 9 baseball players on...

    write a C# program using replit that uses a loop to input # at bats and # of hits for each of the 9 baseball players on a team. Team name, player name, and player position will also be input.(two dimensional array) The program should then calculate and print the individual batting average and, after all 9 players have been entered, calculate and print the team batting average. Example of inputs and Outputs... Enter the Team name: (one time entry)...

  • Java 7.17 Clone of LAB*: Program: Soccer team roster This program will store roster and rating...

    Java 7.17 Clone of LAB*: Program: Soccer team roster This program will store roster and rating information for a soccer team. Coaches rate players during tryouts to ensure a balanced team. (1) Prompt the user to input five pairs of numbers: A player's jersey number (0-99, but this is NOT enforced by the program nor tested) and the player's rating (1-9, not enforced like jersey numbers). Store the jersey numbers in one int array and the ratings in another int...

  • 5.19 Ch 5 Program: Soccer team roster (Vectors) (C++) This program will store roster and rating...

    5.19 Ch 5 Program: Soccer team roster (Vectors) (C++) This program will store roster and rating information for a soccer team. Coaches rate players during tryouts to ensure a balanced team. (1) Prompt the user to input five pairs of numbers: A player's jersey number (0 - 99) and the player's rating (1 - 9). Store the jersey numbers in one int vector and the ratings in another int vector. Output these vectors (i.e., output the roster). (3 pts) Ex:...

  • 5.22 LAB*: Program: Soccer team roster steam This program will store roster and rating information for...

    5.22 LAB*: Program: Soccer team roster steam This program will store roster and rating information for a soccer team Coaches rate players during tryouts to ensure (1) Prompt the user to input five pairs of numbers: A player's jersey number (0.99) and the player's rating (1-9) Store in one int array and the ratings in another int array Output these arrays (e. output the roster) (3 pts) numbers EX Enter player 1 jersey number: Enter player l's rating: Enter player...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT