使用“if else”语句和命名常量在Python中创建函数

2024-09-28 18:54:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码根据球员的位置计算棒球统计数据。你知道吗

这是我需要帮助的代码部分:

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

Tags: andifisdiffitthisavgplayer
1条回答
网友
1楼 · 发布于 2024-09-28 18:54:35

我认为字典可以解决你的问题:

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

测试:

print_player(50, 120, "P")

> This player's batting average is 0.417
> and it is 108.5 percent better than the average Pitcher

相关问题 更多 >