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

时间:2015-10-14 01:46:36

标签: python function

我的代码根据玩家的位置计算棒球统计数据。

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

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.还有&#34;投手&#34;在print语句中被替换。对于每个if else语句,我也有不同的命名常量(P_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")

1 个答案:

答案 0 :(得分:4)

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

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