为每场游戏列出正确的赢家

2024-04-19 12:58:02 发布

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

我正在尝试用Python制作一个程序,它将询问用户5个游戏的分数。然后,我需要在比赛结束时打印出每场比赛的获胜者。我有一个问题的部分是如何在每场比赛中选出合适的获胜者。我只能使用列表、for循环和if/else语句。我是编程新手,所以我不确定自己做错了什么

描述:该程序将接受每支球队在5场比赛中的得分,并将数据与获胜者一起打印出来。获胜的队伍是赢得最多比赛的队伍。注:得分最多的不一定是团队

games = [0, 0, 0, 0, 0]
winner = ["Team 1", "Team 2"]
gamesresults = 0
team1_scores = [0, 0, 0, 0, 0]
team2_scores = [0, 0, 0, 0, 0]
matches = ["Match 1", "Match 2", "Match 3", "Match 4", "Match 5"]

for games in range(5):
    team1_scores[games] = int(input("Enter the score from team 1 from match {}?".format(games+1)))
    team2_scores[games] = int(input("Enter the score from team 2 from match {}?".format(games+1)))
    games += 1

#the section i'm having problems with
for games in range(5):
    if team1_scores[games] > team2_scores[games]:
        winner = "Team 1"
    else:
        winner = "Team 2"

    gamesresults = [team1_scores, team2_scores, winner]

#this is ok
print(" ", "Team 1", "Team 2", "Winner")

for i in range(5):
    print("Matches", i+1, team1_scores[i], team2_scores[i], winner)

if team1_scores > team2_scores:
    print("The Winner is Team 1")
else:
    team2_scores > team1_scores
    print("The Winner is Team 2")

Tags: infromforifmatchrangeelsegames
2条回答

我认为你的代码不是干净的代码,但是这个代码是有用的

games = list()
team1_scores = list()
team2_scores = list()
winner = list()

for games in range(1, 6):
    team1_scores.append(int(input("Enter the score from team 1 from match {}?".format(games))))
    team2_scores.append(int(input("Enter the score from team 2 from match {}?".format(games))))

for team1_score, team2_score in zip(team1_scores, team2_scores):
    if team1_score > team2_score:
        winner.append("Team 1")
    else:
        winner.append("Team 2")

for i in range(len(winner)):
    print("In match {} score of team 1 is : {} and score of team 2 is : {} and winner is {}".format(i+1, team1_scores[i], team2_scores[i], winner[i]))

print("The Winner is " + max(winner))

问题是,您应该计算每个团队赢得的比赛数,而不是覆盖每个for循环中的winner变量

您需要在两个不同的变量中保存每个获胜游戏的计数,然后比较它们:

# save both amounts
won_by_team1 = 0
won_by_team2 = 0
for games in range(5):
    if team1_scores[games] > team2_scores[games]:
        won_by_team1 += 1
    else:
        won_by_team2 += 1


# compare them
if won_by_team1 > won_by_team2:
    winner = "Team 1"
else:
    winner = "Team 2"

这不是一个很好的代码,但它将帮助您理解需要应用的逻辑

一旦您理解了这一点,我建议您重写这段代码,使它看起来更漂亮

如果有帮助,请告诉我

相关问题 更多 >