gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:40:58 27 4
gpt4 key购买 nike

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

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

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。打印语句中的“投手”也被替换。我还为每个 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")

最佳答案

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

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

关于python - 使用 "if else"语句和命名常量在 Python 中创建函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33115299/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com