Python:用于Absolute Beginner“游戏”模块的Python编程中的循环错误

时间:2013-12-29 21:50:50

标签: python loops

我正在学习Python并且在这段代码中遇到了麻烦。我甚至删除了作者的代码,它也有同样的问题。 :(

导入“随机”模块和“游戏”模块(包括“ask_number()”函数和“播放器”的类定义)后,我们有:

again = None
while again != "n":
    players = []
    num = games.ask_number(question = "How many players? (2-5): ", low = 2, high = 5)
    for i in range(num):
        name = input("Player name: ")
        score = random.randrange(100) + 1
        player = games.Player(name, score)
        players.append(player)

“ask_number()”函数如下所示:

def ask_number(question, low, high):
    """Ask for a number within a range."""
    response = None
    while response not in range(low, high):
        response = int(input(question))
    return response

然而,当程序运行时,无论输入什么数字作为响应,都会无限期地出现“多少玩家?(2-5):”这一问题。很明显,似乎已经设置了某种错误的循环,但我无法弄清楚它对我的生活是什么(这就是为什么我是一个“绝对的初学者”,哈哈!)。

提前感谢我恢复理智! :)

EDITED: 因为我认为问题仅仅是使用ask_number()函数的语法,所以我不想附加很多无关的代码。得知那个教训! :)这是完整的循环,所以它似乎再次具有可变值。 (请注意,“ask_yes_no()”函数也在“游戏”模块中。)

again = None
while again != "n":
    players = []
    num = games.ask_number(question = "How many players? (2-5): ", low = 2, high = 5)
    for i in range(num):
        name = input("Player name: ")
        score = random.randrange(100) + 1
        player = games.Player(name, score)
        players.append(player)
    print("\nHere are the game results:")
    for player in players:
        print(player)
    again = games.ask_yes_no("\nDo you want to play again? (y/n): ")

2 个答案:

答案 0 :(得分:2)

你说的是

while again != "n":

但你永远不会再次设置!因为永远不会等于'n'它永远不会退出循环

答案 1 :(得分:0)

您永远不会更改again的值。为了解决这个问题,你可以添加这个

again = raw_input("Play again?: ")

while循环结束时。