<h2>较短的解决方案</h2>
<pre><code>while raw_input("Enjoying the course? (y/n) ") not in ('y', 'n'):
print("Sorry, I didn't catch that. Enter again:")
</code></pre>
<h2>你的代码做错了什么</h2>
<p>关于您的代码,您可以添加一些打印内容,如下所示:</p>
<pre><code>choice = raw_input("Enjoying the course? (y/n) ")
print("choice = " + choice)
student_surveyPromptOn = True
while student_surveyPromptOn:
input = raw_input("Enjoying the course? (y/n) ")
print("input = " + input)
if choice != input:
print("Sorry, I didn't catch that. Enter again:")
else:
student_surveyPromptOn = False
</code></pre>
<p>上面打印出来:</p>
<pre class="lang-none prettyprint-override"><code>Enjoying the course? (y/n) y
choice = y
Enjoying the course? (y/n) n
choice = y
input = n
Sorry, I didn't catch that. Enter again:
Enjoying the course? (y/n) x
choice = y
input = x
Sorry, I didn't catch that. Enter again:
Enjoying the course? (y/n)
</code></pre>
<p>如您所见,在代码中有一个第一步,问题出现,您的答案初始化<code>choice</code>的值。这就是你做错的地方。</p>
<h2>具有<code>!=</code>和<code>loop_condition</code>的解</h2>
<p>如果必须同时使用<code>!=</code>运算符和<code>loop_condition</code>,则应编写代码:</p>
<pre><code>student_surveyPromptOn = True
while student_surveyPromptOn:
choice = raw_input("Enjoying the course? (y/n) ")
if choice != 'y' and choice != 'n':
print("Sorry, I didn't catch that. Enter again:")
else:
student_surveyPromptOn = False
</code></pre>
<p>然而,在我看来,赛博的解决方案和我的更短的解决方案都更优雅(即更Python)。</p>