首页 > 解决方案 > 井字游戏模式有问题?

问题描述

当我运行这段代码时,它只为 j=1 返回 d['a'] 我应该怎么做才能增加 j 的值?

def pattern():
    d = {'a': '   |   |   ', 'b': '--- --- ---'}
    j = 1
    while j <= 11:
        if j not in [4,8]:
            return d['a']
        else:
            return d['b']
        j+=1

标签: python-3.xwhile-looptic-tac-toe

解决方案


我看到您每次执行时都在尝试逐个获取模式。一种替代方法是将所有结果放入一个数组中,然后返回该数组。

def pattern():
    d = {'a': '   |   |   ', 'b': '--- --- ---'}
    j = 1
    result_pattern = []
    while j <= 11:
        if j not in [4,8]:
            result_pattern.append(d['a'])
        else:
            result_pattern.append(d['b'])
        j+=1
    
    # return your array and loop over it after function call.
    return result_pattern 

您将使用如下函数:

p = pattern()
for item in p:
    # do something with your result.

推荐阅读