擅长:python、mysql、java
<p>你把赋值表达式放错地方了。原始循环是无限的,但第二个循环使用<code>answer</code>作为中断条件</p>
<pre><code>while True:
if not (answer := input("Type something: ")):
print("You didn't type anything before pressing Enter!")
continue
print("You typed:", answer)
</code></pre>
<p>同样,因为我们使用的是<code>continue</code>,所以不需要<code>else</code>子句</p>
<p>在行动中:</p>
<pre class="lang-none prettyprint-override"><code>Type something: hello!
You typed: hello!
Type something:
You didn't type anything before pressing Enter!
Type something: hi!
You typed: hi!
</code></pre>
<p>然而,在这里使用walrus操作符并没有真正的优势,所以我会避免使用它</p>
<pre><code>while True:
answer = input("Type something: ")
if not answer:
print("You didn't type anything before pressing Enter!")
continue
print("You typed:", answer)
</code></pre>