【问题标题】:Python Dice Game Points Variables Not ChangingPython骰子游戏点变量不变
【发布时间】:2016-05-25 17:39:32
【问题描述】:
rounds = input()

for i in range(int(rounds)):
    score = input(int())[0:3]
    a = score[0]
    d = score[2]


antonia = 100
david = 100

for scores in score:

    if a < d:
        antonia -= int(a)
    if a > d:
        david -= int(d)
    elif a == d:
        pass

print(antonia)
print(david)

输入期望: 输入的第一行包含整数 n (1 ≤ n ≤ 15),即轮数 将被播放。在接下来的 n 行中的每一行,将是两个整数:该轮 Antonia 的掷骰, 后面是一个空格,然后是该轮的大卫滚动。每卷将是一个整数 介于 1 和 6(含)之间。

输出预期:输出将由两行组成。在第一行,输出 Antonia 拥有的点数 在所有回合都打完之后。在第二行,输出大卫拥有的点数 在所有回合都打完之后。

输入:

  1. 4

  2. 5 6

  3. 6 6
  4. 4 3
  5. 5 2

输出:

  • 100
  • 94

为什么底部值(david)被正确地改变了,但顶部却没有?我对 antonia 做了什么不同的事情,导致它输出的功能与 david 不同?

【问题讨论】:

  • 在第二个循环中,您正在迭代 score,但 ad 永远不会改变。他们保留第一个循环的最后一个值

标签: python function dice


【解决方案1】:

在您的第一个循环中,您不断更新ad。因此,在循环结束时,ad 仅具有与最后一组输入相对应的值。

此外,在您的第二个循环中,您不是遍历所有分数,而是遍历最后一组输入。在继续之前,我建议您回过头来了解您的代码到底在做什么,并跟踪值如何变化。

无论如何,解决问题的一种方法是:

rounds = input("Number of rounds: ")
scores = []
for i in range(int(rounds)):
    score = input("Scores separated by a space: ").split()
    scores.append((int(score[0]), int(score[1]))) #Append pairs of scores to a list

antonia = 100
david = 100

for score in scores:
    a,d = score # Split the pair into a and d
    if a < d:
        antonia -= int(a)
    if a > d:
        david -= int(d)
    elif a == d:
        pass

print(antonia)
print(david)

【讨论】:

    猜你喜欢
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    • 2015-12-24
    相关资源
    最近更新 更多