我正在学习“困难方式” 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()
isinstance(next, (float, int))如果next已经从字符串转换了,它将简单地完成操作。在这种情况下不是。因此,re如果要避免使用,则必须使用进行转换try..except。
isinstance(next, (float, int))
next
re
try..except
我建议使用try..except您之前if..else拥有的代码块,而不是代码块,而是将更多的代码放入其中,如下所示。
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教程。
ValueError