<p>回答你的具体问题</p>
<blockquote>
<p>how can I then put them back at the <code>"Input your number"</code> prompt if they enter an illegal character or they try to overwrite an already placed <code>1</code> or <code>2</code></p>
</blockquote>
<p>我会用一个函数来做这个:</p>
<pre><code>def get_valid_input(board):
while True:
try:
move = int(input("Please enter the number of the position you want to put your symbol."))
except ValueError:
print("Input must be an integer number.")
else:
if move not in range(1, 10):
print("Move must be 1-9.")
elif board[move-1] in (1, 2):
print("Location already used.")
else:
return move
</code></pre>
<p>这将持续到当前任何玩家给出有效的<code>move</code>:</p>
^{pr2}$
<p>一些更一般的建议:</p>
<ul>
<li>你当前对获胜者的检查不起作用-<code>if a or b == c</code>没有像你想的那样做(参见例如<a href="https://stackoverflow.com/questions/15112125/if-x-or-y-or-z-blah">this question</a>)。例如,<code>nr[0] and nr[1] and nr[2] == 2</code>实际上测试<code>bool(nr[0]) and bool(nr[1]) and (nr[2] == 2)</code>;只要最后一个值是2,另外两个不为零,那么它就是<code>True</code>。CoDEmanX在评论中的建议在这里很有用。在</li>
<li>使用标志<code>keepgoing</code>不是很像python;我会创建一个函数<code>game_over(board)</code>,如果游戏结束(无论是赢还是平局),则返回<code>True</code>,否则<code>False</code>,则整个循环变成<code>while True: ... if game_over(board): break</code>。在</li>
<li>不要依赖范围来访问变量,而是显式地传递所需的内容(例如,<code>board</code>参数传递给<code>get_valid_input</code>和{<cd13>})。去掉<code>keepgoing</code>会删除其中一个全局变量,但您可以将<code>board</code>作为其他函数的参数,并根据需要使用<code>return</code>。或者,考虑使用<code>class</code>来保存<code>board</code>和所有函数。在</li>
</ul>