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