【问题标题】:Having problem in Tic-Tac-Toe game pattern?井字游戏模式有问题?
【发布时间】:2021-07-31 03:01:49
【问题描述】:

当我运行这段代码时,它只为 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

【问题讨论】:

  • 一旦你return,方法就结束了。在j1return d['a'] 并且方法完成时的第一个循环。

标签: python-3.x while-loop tic-tac-toe


【解决方案1】:

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

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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多