問題描述
井字遊戲模式有問題? (Having problem in Tic‑Tac‑Toe game pattern?)
當我運行此代碼時,它只為 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
參考解法
方法 1:
I see that you are trying to get the pattern one by one every time look executes. One alternative would be to put all the results in a array and then return the array.
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
You will use your function something like this:
p = pattern()
for item in p:
# do something with your result.
(by Dhruv pratap、Ajay Rathore)