在函数内循环时无法中断 python



这个程序是我的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)

它显然还没有完成,这还不是全部代码。在那之后,它执行相同的操作,但与 player2 相同。它上面有一个元组,检查功能检查玩家是降落在蛇还是梯子上,但我还没有添加实际将玩家向上/向下移动梯子/蛇的代码。

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

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

我在这里和这里寻找答案,但都不适合我;我认为我的情况略有不同。

也许这就是你要找的?请注意我是如何将这些函数从循环中取出的。然后我完全放弃使用布尔变量,因为有更干净的解决方法。您可以使用while True然后简单地break是否满足某个条件。如果希望循环在满足某个条件时返回到起点,可以使用continue

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是有意义的。

发生这种情况是因为当您在函数中分配变量时,它使用了局部变量。因此,为了快速修复,您可以在检查功能中添加global win

def check():
global win
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

您可以在此处阅读有关变量类型的更多信息 - http://www.python-course.eu/python3_global_vs_local_variables.php

此外,将函数存储在内部也不是一个好主意,因为它会在每次迭代时创建函数,这并不好。所以最好在循环之外定义它们。

最新更新