Python:如何使这段代码更简单?

时间:2017-01-29 01:00:10

标签: python python-2.7

我下面有一些代码,choice只接受整数输入,但如果输入不是整数,则输出一些特殊的代码。但是,下面的代码来处理这个问题似乎有点冗长。无论如何要解决它?

from sys import exit

def gold_room():
    print "This room is full of gold.  How much do you take?"

    choice = raw_input("> ")
    if "0" in choice or "1" in choice or "2" in choice or "3" in choice or "4" in choice or "5" in choice or "6" in choice or "7" in choice or "8" in choice or "9" in choice:
        how_much = int(choice)
    else:
        dead("Man, learn to type a number.")

    if how_much < 50:
        print "Nice, you're not greedy, you win!"
        exit(1)
    else:
        dead("You're greedy!")


def dead(why):
    print why, "Good job!"
    exit(0)

gold_room()

2 个答案:

答案 0 :(得分:6)

尝试类似:

try:
    how_much = int(choice)
except ValueError:
    dead('Man, learn to type a number.')

并查找Easier to ask for forgiveness than permission的理由。

答案 1 :(得分:0)

你可以使用str.isdigit()来检查它是否是一个数字,不推荐使用try ... except语句,因为它会使你的代码变得混乱,从长远来看可能会导致错误。但是,如果它只是它也会起作用。

from sys import exit

def gold_room():
    print "This room is full of gold.  How much do you take?"

    choice = raw_input("> ")
    if choice.isdigit(): #Checks if it's a number
        how_much = int(choice)
    else:
        dead("Man, learn to type a number.")
        return

    if how_much < 50:
        print "Nice, you're not greedy, you win!"
        exit(1)
    else:
        dead("You greedy bastard!")


def dead(why):
    print why, "Good job!"
    exit(0)

gold_room()