Question

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 in list1:
#print (list1)
print("-"*64)
print(" | " +x["name"]+" | " +x["position"]+" | "+str(x["at_bats"])+" | "+str(x["hits"])+" | " + "%.3f"%(x["AVG"]))
print("-"*64)
def remove_player():
name=input("Enter name of the player:")
for x in list1:
for k in x.keys():
if name==x[k]:
i=list1.index(x)
del list1[i]
#print(list1)
def edit_player_position():
name=input("Enter name of the player:")
new_position=input("Enter New Position:")
for x in list1:
for k in x.keys():
if name ==x[k]:
i=list1.index(x)
list1[i]["position"]=new_postion
#print(list1)
def edit_player_stats():
name=input("Enter name of the player:")
new_at_bats=int(input("Enter new AB:"))
new_hits=int(input("Enter new H:"))
for x in list1:
for k in x.keys():
if name ==x[k]:
i=list1.index(x)
list1[i]["at_bat"]= new_at_bats
list1[i]["hits"]= new_hits
list1[i]["AVG"]= new_hits/new_at_bats
#print(list1)
def move_player():
name=input("Enter name of the player:")
new_position=input("Enter New Position:")
for x in list1:
for k in x.keys():
if name ==x[k]:
i=list1.index(x)
p=list1.pop(i)
list2.append(p)
#print(list1)
#print(list2)
display()
print("Move to new team")
for x in list2:
print("-"*64)
print(" | " +x["name"]+" | " +x["position"]+" | "+str(x["AB"])+" | "+str(x["hits"])+" | " + "%.3f"%(x["AVG"]))
print("-"*64)
Pos=("C", "1B", "3B", "SS", "LF", "CF", "RF", "P")
ans ="y"
print("POSITIONS:")
for x in Pos:
print (x,end=",")
print()
while ans =="y":
print("-"*64)
print("Baseball Team Manager")
print("MENU OPTIONS:")
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")
ch=int(input ("Enter your choice:"))
if ch==1:
display()
elif ch==2:
add_player()
elif ch==3:
remove_player()
elif ch==4:
move_player()
elif ch==5:
edit_player_position()
elif ch==6:
edit_player_stats()
elif ch==7:
print ("Bye!")
exit()
else:
pass
ans=input("Do you want to continue...(y/n)?")
  
print("Thanks!")



  
  

-Q Search the web 匙Baseball-chap9.py-CAUsers RAOULVAppDataLocanp Il_chap9.py (3.7.3) File Edit Format Run Options Window Hel

a search the web 匙Baseball-chap9.py-CAUsers RAOULVAppDataLocanp File Edit Format Run Options Window Help Il_chap9.py (3.7.3)a search the web 匙Baseball-chap9.py-CAUsers RAOULVAppDataLocanp Il_chap9.py (3.7.3) File Edit Format Run Options Window Help

Improve number and string formatting

Update the program to improve the formatting of the numbers and the strings.

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

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

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 Pence

RF

485

174

0.359

5

Brandon Crawford

SS

532

125

0.235

6

Eduardo Nunez

3B

477

122

0.256

7

Joe Panik

2B

475

138

0.291

8

Jarrett Parker

LF

215

58

0.270

9

Madison Bumgarner

P

103

21

0.204

Menu option: 7

Bye!

!!Specifications !!

-Use the multiplication operator to make sure that horizontal separator lines use 64 characters

-Use spaces, not tabs, to align columns. This should give the program more control over how the columns are aligned.

-Make sure the program always displays the batting average with 3 decimal places. Display the positions by processing the tuple of valid positions.

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

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

               else:

                              d["position"]=""

               at_bats=int(input("Enter AB:"))    

               d["at_bats"] = at_bats

               hits= int(input("Enter H:"))

               d["hits"] = hits

               d["AVG"]= float(float(hits)/at_bats)

               list1.append(d)

              

def display():

               print("{:15} {:8} {:8} {:8} {:8}".format("Player", "Pos", "AB", "H", "AVG"))

               if len(list1) > 0:

                              print("ORIGINAL TEAM")

                              for x in list1:

                                             print("-"*64)

                                             print(" | " +x["name"]+" | " +x["position"]+" | "+str(x["at_bats"])+" | "+str(x["hits"])+" | " + "%.3f"%(x["AVG"]))

                                             print("-"*64)

def remove_player():

               name=input("Enter name of the player:")                              

               for i in range(len(list1)):

                              if name==list1[i]['name']:

                                             del list1[i]

                                             break

def edit_player_position():

               name=input("Enter name of the player:")                              

               new_position=input("Enter New Position:")                          

               for i in range(len(list1)):  

                              if name == list1[i]['name']:

                                             list1[i]["position"]=new_position

                                             break

def edit_player_stats():

               name=input("Enter name of the player:")                              

               new_at_bats=int(input("Enter new AB:"))

               new_hits=int(input("Enter new H:"))

              

               for i in range(len(list1)):

                              if name == list1[i]['name']:

                                             list1[i]["at_bats"]= new_at_bats

                                             list1[i]["hits"]= new_hits

                                             list1[i]["AVG"]= float(float(new_hits)/new_at_bats)

                                             break

def move_player():

               name=input("Enter name of the player:")                              

               for i in range(len(list1)):

                              if name == list1[i]['name']:

                                             p = list1.pop(i)

                                             list2.append(p)

               display()

               print("Move to new team")

               for x in list2:

                              print("-"*64)

                              print(" | " +x["name"]+" | " +x["position"]+" | "+str(x["at_bats"])+" | "+str(x["hits"])+" | " + "%.3f"%(x["AVG"]))

                              print("-"*64)

                             

                             

Pos=("C", "1B", "3B", "SS", "LF", "CF", "RF", "P")

ans ="y"

print("POSITIONS:")

for x in Pos:

               print (x,end=",")               

print()

while ans =="y":

               print("-"*64)

               print("Baseball Team Manager")

               print("MENU OPTIONS:")

               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 the program")

               ch=int(input ("Enter your choice:"))

               if ch==1:

                              display()

               elif ch==2:

                              add_player()

               elif ch==3:

                              remove_player()

               elif ch==4:

                              move_player()

               elif ch==5:

                              edit_player_position()

               elif ch==6:

                              edit_player_stats()

               elif ch==7:

                              print ("Bye!")

                              break

               else:

                              pass

               ans=input("Do you want to continue...(y/n)?")

print("Thanks!")

Code Screenshot:

2 listl- [] 3 list2-[1 5 Edef add player ) d-t name-input (Enter name of the player:) dname1-name position-input (Enter

45 def edit_player_stats : 4 6 name-input (Enter name of the player:) new at bats-int (input (Enter new AB:) new hits-int

69 70 71 (с, IB, Зв, SS, LF Ch, RF, Р) Pos , ansy 73 print(POSITIONS:) 74 for x in Pos: 75 print (x,end-

Add a comment
Know the answer?
Add Answer to:
Something is preventing this python code from running properly. Can you please go through it and...
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...

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

  • I am having trouble with my Python code in this dictionary and pickle program. Here is...

    I am having trouble with my Python code in this dictionary and pickle program. Here is my code but it is not running as i am receiving synthax error on the second line. class Student: def__init__(self,id,name,midterm,final): self.id=id self.name=name self.midterm=midterm self.final=final def calculate_grade(self): self.avg=(self.midterm+self.final)/2 if self.avg>=60 and self.avg<=80: self.g='A' elif self.avg>80 and self.avg<=100: self.g='A+' elif self.avg<60 and self.avg>=40: self.g='B' else: self.g='C' def getdata(self): return self.id,self.name.self.midterm,self.final,self.g CIT101 = {} CIT101["123"] = Student("123", "smith, john", 78, 86) CIT101["124"] = Student("124", "tom, alter", 50,...

  • I need to update this C++ code according to these instructions. The team name should be...

    I need to update this C++ code according to these instructions. The team name should be "Scooterbacks". I appreciate any help! Here is my code: #include <iostream> #include <string> #include <fstream> using namespace std; void menu(); int loadFile(string file,string names[],int jNo[],string pos[],int scores[]); string lowestScorer(string names[],int scores[],int size); string highestScorer(string names[],int scores[],int size); void searchByName(string names[],int jNo[],string pos[],int scores[],int size); int totalPoints(int scores[],int size); void sortByName(string names[],int jNo[],string pos[],int scores[],int size); void displayToScreen(string names[],int jNo[],string pos[],int scores[],int size); void writeToFile(string...

  • python programming: Can you please add comments to describe in detail what the following code does:...

    python programming: Can you please add comments to describe in detail what the following code does: import os,sys,time sl = [] try:    f = open("shopping2.txt","r")    for line in f:        sl.append(line.strip())    f.close() except:    pass def mainScreen():    os.system('cls') # for linux 'clear'    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print(" SHOPPING LIST ")    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print("\n\nYour list contains",len(sl),"items.\n")    print("Please choose from the following options:\n")    print("(a)dd to the list")    print("(d)elete from the list")    print("(v)iew the...

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

  • Can you please enter this python program code into an IPO Chart? import random def menu():...

    Can you please enter this python program code into an IPO Chart? import random def menu(): print("\n\n1. You guess the number\n2. You type a number and see if the computer can guess it\n3. Exit") while True: #using try-except for the choice will handle the non-numbers #if user enters letters, then except will show the message, Numbers only! try: c=int(input("Enter your choice: ")) if(c>=1 and c<=3): return c else: print("Enter number between 1 and 3 inclusive.") except: #print exception print("Numbers Only!")...

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

  • Can you add code comments where required throughout this Python Program, Guess My Number Program, and...

    Can you add code comments where required throughout this Python Program, Guess My Number Program, and describe this program as if you were presenting it to the class. What it does and everything step by step. import random def menu(): #function for getting the user input on what he wants to do print("\n\n1. You guess the number\n2. You type a number and see if the computer can guess it\n3. Exit") while True: #using try-except for the choice will handle the...

  • Python 3 Question: All I need is for someone to edit the program with comments that...

    Python 3 Question: All I need is for someone to edit the program with comments that explains what the program is doing (for the entire program) def main(): developerInfo() #i left this part out retail = Retail_Item() test = Cash_Register() test.data(retail.get_item_number(), retail.get_description(), retail.get_unit_in_inventory(), retail.get_price()) answer = 'n' while answer == 'n' or answer == 'N': test.Menu() print() print() Number = int(input("Enter the menu number of the item " "you would like to purchase: ")) if Number == 8: test.show_items() else:...

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