如何检查用户输入是否为浮点数
我正在做《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()
6 个回答
0
使用下面的基于Python的正则表达式来检查浮点数字符串。
import re
a=re.match('((\d+[\.]\d*$)|(\.)\d+$)' , '2.3')
a=re.match('((\d+[\.]\d*$)|(\.)\d+$)' , '2.')
a=re.match('((\d+[\.]\d*$)|(\.)\d+$)' , '.3')
a=re.match('((\d+[\.]\d*$)|(\.)\d+$)' , '2.3sd')
a=re.match('((\d+[\.]\d*$)|(\.)\d+$)' , '2.3')
输出结果是:!None, !None, !None, None, !None。然后可以利用这个输出进行转换。
1
1
我对你这种做法有点问题,因为你走的是“先看再跳”的路,而不是更符合Python风格的“问原谅比请求许可更简单”的方式。我觉得你最开始的解决方案比这样验证输入要好。
下面是我会写的方式。
GREEDY_LIMIT = 50
def gold_room():
print("This room is full of gold. What percent of it do you take?")
try:
how_much = float(raw_input("> "))
except ValueError:
print("Man, learn to type a number.")
gold_room()
return
if how_much <= GREEDY_LIMIT:
print "Nice, you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
1
RE会是一个不错的选择
>>> re.match("^\d+.\d+$","10")
>>> re.match("^\d+.\d+$","1.00001")
<_sre.SRE_Match object at 0x0000000002C56370>
如果输入的是一个浮点数,它会返回一个对象。否则,它会返回None。如果你需要识别整数,你可以:
>>> re.match("^[1-9]\d*$","10")
<_sre.SRE_Match object at 0x0000000002C56308>
3
isinstance(next, (float, int))
这个方法可以简单地检查 next
是否已经被转换成了数字(浮点数或整数)。但在这个情况下,它并没有被转换。所以如果你想避免使用 try..except
,你就得用 re
来进行转换。
我建议你还是使用之前的 try..except
结构,而不是 if..else
,不过可以把更多的代码放进去,像下面这样。
def gold_room():
while True:
print "This room is full of gold. What percent of it do you take?"
try:
how_much = float(raw_input("> "))
if how_much <= 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
except ValueError:
print "Man, learn to type a number."
这样做会尝试把它转换成浮点数,如果失败了,就会抛出一个 ValueError
,这个错误会被捕获。想了解更多,可以查看 Python教程。