これは、私が学んだいくつかの新しいことをテストするために書いた小さなプログラムのコードです。
while 1:
try:
a = input("How old are you? ")
except:
print "Your answer must be a number!"
continue
years_100 = 100 - a
years_100 = str(years_100)
a = str(a)
print "You said you were "+a+", so that means you still have "+years_100+" years"
print "to go until you are 100!"
break
while 2:
try:
b = str(raw_input('Do you want to do it again? If yes enter "yes", otherwise type "no" to stop the script.'))
except:
print 'Please try again. Enter "yes" to do it again, or "no" to stop.'
continue
if b == "yes":
print 'You entered "yes". Script will now restart... '
elif b == "no":
print 'You entered "no". Script will now stop.'
break
forループでは正常に機能します。数字以外のものを入力すると、数字のみが許可されていることがわかります。
ただし、2番目のループでは、yesまたはnoの入力を求められますが、別の入力を入力すると、メッセージを出力するのではなく、ループを再開するだけです。
except:
何を間違えたのでしょうか。また、伝えたメッセージが表示されるように修正するにはどうすればよいですか。