私は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)