我正在进行“Learn 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()
next
用作变量名,因为它是Python中的一个函数。 - dawg