gpt4 book ai didi

Python:绝对初学者Python编程 "games"模块中的循环错误

转载 作者:行者123 更新时间:2023-12-01 05:28:37 26 4
gpt4 key购买 nike

我正在学习 Python,但在这段代码中遇到了障碍。我什至拉下了作者的代码,它也有同样的问题。 :(

导入“random”模块和“games”模块(其中包括“ask_number()”函数和“Player”的类定义)后,我们有:

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):”都会无限出现。显然,似乎已经建立了某种错误的循环,但我无法弄清楚它对我的生活意味着什么(这就是为什么我是一个“绝对的初学者”,哈哈!)。

预先感谢您让我恢复理智! :)

编辑:由于我认为问题仅仅是与 Ask_number() 函数的语法有关,因此我不想附加大量无关的代码。吸取了教训! :) 这是完整的循环,所以看起来确实再次有一个可变的值。 (请注意,“ask_yes_no()”函数也在“games”模块中。)

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): ")

最佳答案

你说的是

while again != "n":

但你再也没有设置过!因为再次永远不等于“n”,所以它永远不会退出循环

关于Python:绝对初学者Python编程 "games"模块中的循环错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20830455/

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