3

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

6 回答 6

3

isinstance(next, (float, int))如果next已经从字符串转换,则可以解决问题。在这种情况下不是。因此,re如果您想避免使用try..except.

我建议使用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将被捕获的 a。要了解更多信息,请参阅Python 教程

于 2014-04-25T22:13:00.010 回答
1

RE将是一个不错的选择

>>> 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>
于 2014-04-25T22:13:04.133 回答
1

您可以使用正则表达式来验证格式:

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

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

于 2014-04-25T22:13:09.230 回答
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!")
于 2014-04-25T22:24:47.130 回答
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 然后使用此输出进行转换。

于 2017-02-24T11:03:42.157 回答
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!")
于 2019-05-16T14:41:48.627 回答