【问题标题】:Having the right winner listed for each game Python为每个游戏列出正确的获胜者 Python
【发布时间】:2020-03-04 09:32:17
【问题描述】:

我正在尝试使用 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")

【问题讨论】:

  • 游戏规则是什么,比如获胜者是如何决定的?是总分最高还是别的什么?
  • 程序将接受每支球队在 5 场比赛中的得分,并将数据与获胜者一起打印出来。获胜的球队是赢得比赛最多的球队。注意:不一定是得分最多的球队。
  • 我遇到的问题是让每场比赛的正确获胜者打印出来。你能说得更具体点吗?

标签: python list for-loop if-statement


【解决方案1】:

问题是您应该计算每支球队赢得的比赛次数,而不是在每个 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"

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

一旦您理解了这一点,我建议您重写此代码以使其看起来更好。

如果有帮助请告诉我!

【讨论】:

  • 谢谢!这对我帮助很大
【解决方案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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 2013-02-11
    相关资源
    最近更新 更多