我的代码根据球员的位置计算棒球统计数据。你知道吗
这是我需要帮助的代码部分:
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")
我有同样的东西8次以上,但我用不同的位置(C,1B,LF等)取代p。此外,print语句中的“pitcher”也被替换。对于每个if-else语句,我也有不同的命名常量(本例中的P\u AVG)。我试图创建一个函数,这样我就不必重写同一件事8次,只有轻微的调整。在课堂上,我们学习了for循环函数的例子,但我不知道如何开始这个例子。你知道吗
编辑: 下面是另一个if语句的样子:
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")
我认为字典可以解决你的问题:
测试:
相关问题 更多 >
编程相关推荐