如何检查用户输入是否为浮动

发布于 2021-01-29 15:04:58

我正在学习“困难方式” Python35。下面是原始代码,我们被要求对其进行更改,以便它可以接受其中不包含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()
关注者
0
被浏览
157
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    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被捕获的浮点数。要了解更多信息,请参见Python教程



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看