我正在学习 Python the Hard Way 练习 35。下面是原始代码,我们被要求更改它,以便它可以接受其中不只有 0 和 1 的数字。
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!")
这是我的解决方案,它运行良好并识别浮点值:
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!")
通过搜索类似的问题,我找到了一些帮助我编写另一个解决方案的答案,如下面的代码所示。问题是,使用 isdigit() 不会让用户输入浮点值。因此,如果用户说他们想拿 50.5%,它会告诉他们学习如何输入数字。它适用于整数。我怎样才能解决这个问题?
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()