2

これは、私が学んだいくつかの新しいことをテストするために書いた小さなプログラムのコードです。

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:

何を間違えたのでしょうか。また、伝えたメッセージが表示されるように修正するにはどうすればよいですか。

4

1 に答える 1

4

を使用するときは常に文字列を入力するため、例外は発生しませんraw_input()。したがってstr()、の戻り値はraw_input()失敗することはありません。

代わりに、またはテストelseにステートメントを追加してください。yesno

if b == "yes":
        print 'You entered "yes". Script will now restart... '
elif b == "no":
        print 'You entered "no". Script will now stop.' 
        break
else:
    print 'Please try again. Enter "yes" to do it again, or "no" to stop.'
    continue

except包括的なステートメントは絶対に使用しないでください。特定の例外をキャッチします。そうしないと、無関係な問題がマスクされ、それらの問題を見つけるのが難しくなります。

最初のexceptハンドラーはNameErrorEOFErrorをキャッチするだけで済みSyntaxErrorます。たとえば、次のようになります。

try:
    a = input("How old are you? ")
except (NameError, SyntaxError, EOFError):
    print "Your answer must be a number!"
    continue

input()それが投げるものなので。

また、 Python式input()使用することにも注意してください。(引用符で)入力する"Hello program"と、例外は発生しませんが、数値でもありません。代わりに使用int(raw_input())してから、catch ValueError(整数以外のものを入力した場合にスローされるもの)とEOFErrorfor raw_input

try:
    a = int(raw_input("How old are you? "))
except (ValueError, EOFError):
    print "Your answer must be a number!"
    continue

True2番目のループを使用して最初のループを制御するには、またはFalse:を返す関数にします。

def yes_or_no():
    while True:
        try:
            cont = raw_input('Do you want to do it again? If yes enter "yes", otherwise type "no" to stop the script.'))
        except EOFError:
            cont = ''  # not yes and not no, so it'll loop again.
        cont = cont.strip().lower()  # remove whitespace and make it lowercase
        if cont == 'yes':
            print 'You entered "yes". Script will now restart... '
            return True
        if cont == 'no':
            print 'You entered "no". Script will now stop.' 
            return False
        print 'Please try again. Enter "yes" to do it again, or "no" to stop.'

そして他のループでは:

while True:
    # ask for a number, etc.

    if not yes_or_no():
        break  # False was returned from yes_or_no
    # True was returned, we continue the loop
于 2013-01-18T22:53:28.940 に答える