<p>我正在做学习Python的艰苦方式练习35。下面是原始代码,我们被要求更改它,以便它可以接受不只有0和1的数字。</p>
<pre class="lang-python prettyprint-override"><code>def gold_room():
print "This room is full of gold. How much do you take?"
next = raw_input("> ")
if "0" in next or "1" in next:
how_much = int(next)
else:
dead("Man, learn to type a number.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
</code></pre>
<p>这是我的解决方案,运行良好并识别浮点值:</p>
<pre class="lang-python prettyprint-override"><code>def gold_room():
print "This room is full of gold. What percent of it do you take?"
next = raw_input("> ")
try:
how_much = float(next)
except ValueError:
print "Man, learn to type a number."
gold_room()
if how_much <= 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
</code></pre>
<p>通过搜索类似的问题,我找到了一些帮助我编写另一个解决方案的答案,如下面的代码所示。问题是,使用isdigit()不允许用户输入浮点值。所以,如果用户说他们想占50.5%,它会告诉他们如何输入一个数字。否则它对整数起作用。我怎么能避开这个?</p>
<pre class="lang-python prettyprint-override"><code>def gold_room():
print "This room is full of gold. What percent of it do you take?"
next = raw_input("> ")
while True:
if next.isdigit():
how_much = float(next)
if how_much <= 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
else:
print "Man, learn to type a number."
gold_room()
</code></pre>