Question

Write a Python program that stores the data for each player on the team, and it...

Write a Python program that stores the data for each player on the team, and it also lets the manager set a starting lineup for each game.

Questions:

- 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.

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

Console

================================================================

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

Team data file could not be found.

You can create a new one if you want.

================================================================

Menu option: 2

Name: Mike

Position: SS

At bats: 0

Hits: 0

Mike was added.

Menu option: X

Not a valid option. Please try again.

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

Menu option: 7

Bye!

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("Bye!")

                                            

               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:

Output:

Add a comment
Know the answer?
Add Answer to:
Write a Python program that stores the data for each player on the team, and it...
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
  • Chapter 8 Python Case study Baseball Team Manager For this case study, you’ll use the programming...

    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,...

  • Help me figure this problem out, please. Use a list to store the players Update the...

    Help me figure this problem out, please. Use a list to store the players Update the program so that it allows you to store the players for the starting lineup. This should include the player’s name, position, at bats, and hits. In addition, the program should calculate the player’s batting average from at bats and hits. Console ================================================================ Baseball Team Manager MENU OPTIONS 1 – Display lineup 2 – Add player 3 – Remove player 4 – Move player 5...

  • 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...

  • 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...

  • 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 program that stores the following data in a tuple: 54,76,32,14,29,12,64,97,50,86,43,12 The program needs to...

    Write a program that stores the following data in a tuple: 54,76,32,14,29,12,64,97,50,86,43,12 The program needs to display a menu to the user, with the following 4 options: 1 – Display minimum 2 – Display maximum 3 – Display total 4 – Display average 5 – Quit Make your program loop back to this menu until the user chooses option 5. Write code for all 4 other menu choices using the python code and screenshot the python code for me. many...

  • In C Program This program will store the roster and rating information for a soccer team. There w...

    In C Program This program will store the roster and rating information for a soccer team. There will be 3 pieces of information about each player: Name: string, 1-100 characters (nickname or first name only, NO SPACES) Jersey Number: integer, 1-99 (these must be unique) Rating: double, 0.0-100.0 You must create a struct called "playData" to hold all the information defined above for a single player. You must use an array of your structs to to store this information. You...

  • Can you please Test and debug the program below using the following specifications? Many thanks! Create...

    Can you please Test and debug the program below using the following specifications? Many thanks! Create a list of valid entries and the correct results for each set of entries. Then, make sure that the results are correct when you test with these entries. Create a list of invalid entries. These should include entries that test the limits of the allowable values. Then, handle the invalid integers (such as negative integers and unreasonably large integers). In addition, make sure the...

  • Using PYTHON create a program to allow the user to enter a phrase or read a...

    Using PYTHON create a program to allow the user to enter a phrase or read a file. Make your program menu-driven to allow the user to select a option to count the total words in the phrase or file. In addition, provide a menu-selection to count the number of words start with a vowel and a selection to count the number of words that start with a consonant. Include exception handlers for file not found, divide by zero, and index...

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