2

My code calculates baseball statistics based on the player's position.

This is the part of my code I need help with:

if position=="P":
    finalBA=totalHits/totalAtBats
    diff=finalBA-P_AVG
    percentChange=diff/P_AVG*100
    if finalBA<P_AVG:
        print("This player's batting average is", round(finalBA, 3),"and it is", abs(round(percentChange, 1)),"percent worse than the average Pitcher")
    else:
        print("This player's batting average is", round(finalBA, 3),"and it is", (round(percentChange, 1)),"percent better than the average Pitcher")

I have the same thing 8 more times but I replaced P with different positions (C, 1B, LF, etc.). Also "pitcher" is replaced in the print statement. I also have different named constants for each if else statement (P_AVG is the one seen in this example). I am trying to create a function so I don't have to rewrite the same thing 8 times with only minor tweaks. In class, we learned examples of functions with for loops, but I'm not sure how to get this one started.

Edit: Here is what one of the other if statements looks like:

elif position=="3B":
    finalBA=totalHits/totalAtBats
    diff=finalBA-TB_AVG
    percentChange=diff/TB_AVG*100
    if finalBA<TB_AVG:
        print("This player's batting average is", round(finalBA, 3),"and it is", abs(round(percentChange, 1)),"percent worse than the average Third Baseman")
    else:
        print("This player's batting average is", round(finalBA, 3),"and it is", (round(percentChange, 1)),"percent better than the average Third Baseman")
A Butler
  • 99
  • 3
  • 9

1 Answers1

4

I think a dictionary would solve your problem:

positions = {
    "P": {"name": "Pitcher","avg": 0.200},
    "C": {"name": "Catcher","avg": 0.404},
    "1B": {"name": "1st Base","avg": 0.224},
    "2B": {"name": "2nd Base","avg": 0.245},
    "3B": {"name": "3rd Base","avg": 0.333},
    "SS": {"name": "Short Stop","avg": 0.234},
    "LF": {"name": "Left Field","avg": 0.240},
    "CF": {"name": "Center Field","avg": 0.200},
    "RF": {"name": "Right Field","avg": 0.441}
}
def print_player(hits, at_bats, pos):
    position = positions[pos]
    ba = round(float(hits) / at_bats, 3)
    pa = round(position["avg"], 3)
    diff = abs(round((ba - pa) / pa * 100, 1))
    comp = "worse than" if ba < pa else "better than" if ba > pa else "equal to"
    print """
          This player's batting average is {} 
          and it is {} percent {} the average {}
          """.format(ba, diff, comp, position["name"])

A test:

print_player(50, 120, "P")

> This player's batting average is 0.417
> and it is 108.5 percent better than the average Pitcher
Steven Moseley
  • 15,871
  • 4
  • 39
  • 50