求助:如何改写不含break语句的Python循环代码?
无break版本的Python代码改写方案
以下是去掉所有break语句后的代码,通过控制变量和循环条件替代原逻辑:
import random # 假设check_win和print_table是已定义的游戏核心函数 def check_win(table): # 示例胜利判定逻辑,可根据实际游戏规则调整 for row in table: if all(cell == "SEEN" for cell in row): return True for col in range(3): if all(table[row][col] == "SEEN" for row in range(3)): return True if table[0][0] == table[1][1] == table[2][2] == "SEEN": return True if table[0][2] == table[1][1] == table[2][0] == "SEEN": return True return False def print_table(table): for row in table: print(" | ".join(row)) print() # 初始化示例数据(可根据实际需求替换) contents = ["A", "B", "C", "D", "E", "F", "G", "H", "I"] table = [["A", "B", "C"], ["D", "E", "F"], ["G", "H", "I"]] game_active = True while game_active: choice = input("Is it time to choose(Y/N)? ") if choice.upper() == "N": game_active = False else: # 修正原代码潜在索引越界问题:randint为闭区间,范围应设为0到len(contents)-1 idx = random.randint(0, len(contents)-1) fnd = False i = 0 # 用while循环+条件替代外层for的break while i < 3 and not fnd: j = 0 # 用while循环+条件替代内层for的break while j < 3 and not fnd: if table[i][j] == contents[idx]: table[i][j] = "SEEN" fnd = True j += 1 i += 1 won = check_win(table) print_table(table) if won: print("The game has been won!!") game_active = False
关键改动说明:
- 外层循环控制:用
game_active布尔变量替代while True的无限循环,当输入"N"或游戏胜利时,将game_active设为False,循环自动终止。 - 嵌套查找逻辑:把原双层
for循环改为while循环,通过fnd变量和计数器范围(i < 3、j < 3)控制循环是否继续。找到目标位置后fnd变为True,后续循环条件不满足,自然退出,完全替代原break的功能。 - 索引修复:原代码中
random.randint(0, len(contents))会触发列表索引越界(列表最大索引为len(contents)-1),已同步修正范围。
内容的提问来源于stack exchange,提问作者A Z
相关产品推荐
相关产品推荐

