如何检查用户输入是否为浮点数?

3

我正在进行“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()

3
不要将next用作变量名,因为它是Python中的一个函数。 - dawg
6个回答

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教程


我尝试了这段代码,它运行良好。谢谢。这是一个很好的解决方案,但由于他还没有介绍try/except语句,我认为Slick提供的答案更符合作者的要求。 - pez
@pez Slick 也使用 try except。 - Chris Hagmann
抱歉,我看错了其他东西。是的,那么你们两个的代码都是合适和高效的。 - pez

1
我对你的方法有所疑虑,因为你正在走“先看再跳”的路线,而不是更Pythonic的“宁愿请求原谅也不要事先获准”的路线。我认为你最初的解决方案比尝试以这种方式验证输入更好。
以下是我的写法。
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!")

你的代码简单高效,运行良好。谢谢。到目前为止,我最喜欢这个答案,因为它没有使用我还未学习到的任何概念。他还没有介绍try/except语句,所以我认为这个答案符合他对我们期望的要求。 - pez
@pez 如果你发现一个答案有用,表达出来的好习惯是给它点赞(可以点赞多个答案),最终甚至接受一个答案(只能接受一个)。 - Jan Vlcinsky
@ Jan Vlcinsky 感谢您的建议。我还不能点赞,因为我是新用户,需要达到15个声望才能进行此操作。由于有多个答案是有效的,所以我正在考虑接受哪一个答案。 - pez
这是错误的。当你在except子句的末尾调用gold_room()时,你正在启动一系列递归调用,如果用户输入非浮点值,则会导致意外行为。 - dawg

1

正则表达式是一个不错的选择

>>> 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>

1

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')

输出:!无,!无,!无,无,!无 然后使用此输出进行转换。


1
为什么要点踩?它是所有已发布解决方案中最好的解决方案,你能否给出理由而不仅仅是点踩! - donald

0
如果您不想使用try/except,以下是我的答案:
def gold_room():
    print "This room is full of gold. How much do you take?"

    choice = input("> ")

    if choice.isdigit():
        how_much = int(choice)
    elif "." in choice:
        choice_dot = choice
        choice_dot_remove = choice_dot.replace(".","")
        if choice_dot_remove.isdigit():
            how_much = float(choice)

    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!")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接