2017-01-29 7 views
-2

私は以下のコードをいくつか持っていますが、choiceは整数入力だけをとりますが、入力が整数でない場合は特別なものを出力します。しかし、この問題を扱う以下のコードはちょっと長いようです。とにかくそれを修正するには?Python:このコードを簡単にする方法は?

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() 
+0

この質問は、おそらく[コードレビュースタック交換](https://codereview.stackexchange.com/)に適しています。 –

+0

かなり長いif文についてお話していると思いますか?組み込み関数 'any'を見てください。それにもかかわらず、必要に応じて(単に削除された回答のように)例外をキャッチして、 'int'への変換を行うことをお勧めします。 –

+0

'choice == '1a''ならば? –

答えて

6

ような何か試してみてください:

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

をし、根拠のためEasier to ask for forgiveness than permissionを見上げます。

+0

分で私を打つ。 :)私は削除されます。 –

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() 
関連する問題