0

私はPythonを学んでいて、whileループに埋め込まれたtry/exceptおよびif/elseを使用するのではなく、これをコーディングするためのより良い方法があるかどうかを知りたいと思っていました. これは難しい方法でコーディングすることを学ぶことから来ており、ユーザーに数字を入力する機会を 3 回与えようとしています。3 回目のチャンスでは、dead 関数を使用して終了します。(コメントは私自身のためのものでした)

def gold_room():
    print "this room is full of gold. How much do you take?"
    chance = 0 #how many chances they have to type a number
    while True: #keep running
        next = raw_input("> ")
        try:
            how_much = int(next) #try to convert input to number
            break #if works break out of loop and skip to **
        except: #if doesn't work then
            if chance < 2: #if first, or second time let them try again
                chance += 1
                print "Better type a number..."
            else: #otherwise quit
                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 dead(why):
    print why, "Good bye!"
    exit(0)
4

2 に答える 2

1

再帰を使用した別のアプローチを次に示します。

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

def typenumber(attempts):
    if attempts:
        answer = raw_input('> ')
        try:
            int(answer)
        except ValueError:
            print "Better type a number..."
            return typenumber(attempts -1)
        else:
            return True

if typenumber(3):
    print 'you got it right'
else:
    dead("Man, learn to type a number.")


> a
Better type a number...
> b
Better type a number...
> 3
you got it right

これはあなたが提供したもののスリム化されたバージョンであり、フレーバー テキストの多くが欠落していますが、値をハード コードせずにカプセル化するための他のアプローチについて、さらに洞察を提供できることを願っています。

于 2013-03-27T23:32:16.837 に答える
-1

tryあなたをループに入れる代わりに、whileおそらく while ループを の中に移動してexcept、Python の前提であるコードをより体系的で読みやすくします。コピーして実行できる実際の例を次に示します。

def gold_room():
    print "this room is full of gold. How much do you take?"
    while True: #keep running
        next = raw_input("> ")
        try:
            how_much = int(next) #try to convert input to number
            break #if works break out of loop and skip to **
        except: #if doesn't work then
            while True:
                chance = 0 #how many chances they have to type a number
                if chance < 2: #if first, or second time let them try again
                    chance += 1
                    print "Better type a number..."
                else: #otherwise quit
                    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 dead(why):
    print why, "Good bye!"
    exit(0)

gold_room()
于 2013-03-27T23:38:34.363 に答える