gpt4 book ai didi

python - 无法中断函数内的 python while 循环

转载 作者:行者123 更新时间:2023-12-01 02:41:23 25 4
gpt4 key购买 nike

这个程序是我的 GCSE 计算机科学的蛇梯程序(别担心,这只是练习),我在使用循环内存在的函数打破 while 循环时遇到了麻烦。代码如下:

win = False

while win == False:
print("Player 1 goes first.")

def dice():
roll = random.randint(1,6)
return roll

roll = dice()
print("They roll a...",roll)
player1+=roll

def check():
if player1 in ladders or player2 in ladders:
print("A ladder has moved the player to a new position.")
elif player1 in snakes or player2 in snakes:
print("A snake has moved the player to a new position.")
elif player1 >= 36:
print("Congratulations. Player 1 has won the game.")
win = True
elif player2 >= 36:
print("Congratulations. Player 2 has won the game.")
win = True

check()

print("Player 1 is on square",player1)

显然还没有完成,而且这还不是全部代码。在那之后,它会做同样的事情,但对玩家 2 来说。上面有一个元组,检查函数检查玩家是否落在蛇或梯子上,但我没有添加实际使玩家在梯子/蛇上上下移动的代码。

错误在于while循环是无限循环。

我尝试将整个 win = False 或 True 的内容更改为 while True ,然后在我说 win = True 的地方使用break,但随后它会返回“中断外部循环”的错误,即使中断显然在内部循环。我想知道这是否是因为我需要从函数返回一些东西,但我不太确定该怎么做。简单地将“return win”放在 win = True 下方不会改变任何内容,并且 while 循环仍然无限期地继续。

我看过herehere寻求答案,但都不适合我;我认为我的情况略有不同。

最佳答案

也许这就是您正在寻找的东西?请注意我如何将函数从循环中取出。然后我完全放弃使用 bool 变量,因为有更干净的方法可以解决它。您可以使用while True,然后在满足特定条件时简单地break。如果您希望循环在满足某个条件时回到起点,可以使用继续

def dice():
return random.randint(1,6)


def check():
if player1 in ladders or player2 in ladders:
print("A ladder has moved the player to a new position.")
elif player1 in snakes or player2 in snakes:
print("A snake has moved the player to a new position.")
elif player1 >= 36:
print("Congratulations. Player 1 has won the game.")
return True
elif player2 >= 36:
print("Congratulations. Player 2 has won the game.")
return True

while True:
print("Player 1 goes first.")

roll = dice()
print("They roll a...",roll)
player1 += roll

if check():
break

print("Player 1 is on square",player1)

我并没有真正触及逻辑,但将玩家得分传递给check是有意义的。

关于python - 无法中断函数内的 python while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45672003/

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