我正在做学习Python的艰苦方式练习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()
是个不错的选择
如果原始输入是浮点数,它将返回一个对象。否则,它将不返回任何内容。如果需要识别int,可以:
您可以使用regex验证格式:
您可以在这里找到文档:https://docs.python.org/2/library/re.html
只要
next
已经从字符串转换过来,isinstance(next, (float, int))
就可以做到这一点。不是在这种情况下。因此,如果要避免使用try..except
,就必须使用re
来进行转换。我建议您使用以前的
try..except
块,而不是if..else
块,但要将更多的代码放入其中,如下所示。这将尝试将其转换为一个浮点数,如果失败,将引发一个将被捕获的
ValueError
。要了解更多信息,请参见上面的Python Tutorial。相关问题 更多 >
编程相关推荐