擅长:python、mysql、java
<p>这不起作用,因为:</p>
<p>在Python中,<code>bool(…)</code>为所有非空字符串返回<code>True</code>。例如:</p>
<pre class="lang-py prettyprint-override"><code>>>> bool("")
False
>>> bool("foo")
True
>>> bool("yes")
True
>>> bool("no")
True
>>> bool("False")
True
</code></pre>
<p>要解决此问题,您可以</p>
<ol>
<li>定义自己的<code>str_bool</code>函数,例如</li>
</ol>
<pre class="lang-py prettyprint-override"><code>def str_bool(s):
if s.lower() in ["y", "yes", "yeah", "true", "positive", "1"]:
return True
elif s.lower() in ["n", "no", "nope", "false", "negative", "0"]:
return False
else:
raise ValueError("string %s is not bool-able" % s)
</code></pre>
<ol start=“2”>
<li>将条件评估的结果分配给<code>rain</code>变量:</li>
</ol>
<pre class="lang-py prettyprint-override"><code>rain = input('is it raining outside?: ').lower() in ["yes", "y", "yeah", "positive", "1"]
if rain:
print("I'm going to dance in the rain!")
else:
print ("I'm going to dance in the sun!")
</code></pre>
<p>第二个当然不能处理用户输入<code>maybe</code>的情况——第一个显然更好更干净</p>