如何检查用户输入是否为

2024-05-12 20:58:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做学习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()

Tags: ofyouifisdefthiselsehow
3条回答

是个不错的选择

>>> re.match("^\d+.\d+$","10")
>>> re.match("^\d+.\d+$","1.00001")
<_sre.SRE_Match object at 0x0000000002C56370>

如果原始输入是浮点数,它将返回一个对象。否则,它将不返回任何内容。如果需要识别int,可以:

>>> re.match("^[1-9]\d*$","10")
<_sre.SRE_Match object at 0x0000000002C56308>

您可以使用regex验证格式:

r'^[\d]{2}\.[\d]+$'

您可以在这里找到文档:https://docs.python.org/2/library/re.html

只要next已经从字符串转换过来,isinstance(next, (float, int))就可以做到这一点。不是在这种情况下。因此,如果要避免使用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 Tutorial

相关问题 更多 >