1

数値の入力を受け入れて、確認するスクリプトを作成しようとしています。

(a)入力が実際には数値であり、(b)問題の数値が17以下であること。

私はさまざまな「if」ステートメントを無駄に試しましたが、今は「try」ステートメントに頭を悩ませようとしています。これは、これまでの私の最善の試みです。

def listlength():
    print "How many things (up to 17) do you want in the list?"
    global listlong
    listlong = raw_input("> ")
    try:
        listlong = int(listlong)
        listlong <= 17
    except:
        print "Gotta be a number less than 17, chumpy!"
        listlength()
    liststretcher()

これは、試行の最初の要素に対して機能します。数値でない場合は、listlength関数を再度実行する必要があります。ただし、2番目の要素(<= 17)は完全に無視されます。

私も試しました

try:
    listlong = int(listlong) and listlong <= 17

...しかし、それでも機能的な最初のチェックしか得られず、2番目のチェックは完全に無視されます。

2つのtryステートメントがある場合も同じ結果が得られます。

    try:
        listlong = int(listlong)
    except:
        print "Gotta be a number, chumpy!"
        listlength()
    try: 
        listlong <=17
    except: 
        print "Gotta be less than 17!"
        listlength()
    liststretcher() 

試してみる方法はありますか:2つのことを確認し、例外を通過する前に両方を通過する必要がありますか?または、liststretcher()コマンドに進む前に、同じ定義のステートメントを2つ試してみる必要がありますか?

以下のS.Lottに応えて、私の意図は、「try:listlong <= 17」が、「listlong」変数が17以下であるかどうかを確認することでした。そのチェックが失敗した場合は、「例外」に移動します。合格すると、以下のliststretcher()に移動します。

これまでの回答を読んで、フォローアップするものが約8つあります...

4

6 に答える 6

2

あなたはほとんどの答えを持っています:

def isIntLessThanSeventeen(listlong):
    try:
        listlong = int(listlong) # throws exception if not an int
        if listlong >= 17:
            raise ValueError
        return True
    except:
        return False

print isIntLessThanSeventeen(16) # True
print isIntLessThanSeventeen("abc") # False
于 2012-02-28T17:58:02.510 に答える
1

関係を確認するにはifステートメントを使用する必要があり、必要に応じて手動で例外を発生させます。

于 2012-02-28T17:58:47.490 に答える
1

あなたが見逃していること、そしてS.Lottがあなたを導こうとしていることは、その声明listlong <= 17が例外を提起しないということです。これは、TrueまたはFalseのいずれかを生成する単なる条件式であり、その値は無視します。

つまり、おそらく、はassert( listlong <= 17 )、条件がFalseの場合にAssertionError例外をスローします。

于 2012-02-28T18:36:23.133 に答える
0
length = ""
while not length.isdigit() or int(length) > 17:
   length = raw_input("Enter the length (max 17): ")
length = int(length)
于 2012-02-28T18:27:36.907 に答える
0

さて、あなたの解決策を修正するには:

def listlength():
    print "How many things (up to 17) do you want in the list?"
    global listlong
    listlong = raw_input("> ")
    try:
        listlong = int(listlong)
        listlong <= 17
    except:
        print "Gotta be a number less than 17, chumpy!"
        listlength()
        return
    liststretcher()

問題は、必要のないときに再帰を使用していることです。次のことを試してください。

def listlength():
    print "How many things (up to 17) do you want in the list?"
    global listlong
    listlong = raw_input("> ")
    value = None
    while value is None or and value > 17:
            try:
                listlong = int(listlong)
            except:
                print "Gotta be a number less than 17, chumpy!"
                value = None
    listlong = value
    liststretcher()

そうすれば、関数はそれ自体を呼び出さず、liststretcherの呼び出しは、入力が有効な場合にのみ発生します。

于 2012-02-28T18:01:42.700 に答える
0

再帰を回避する理由はありません。これも機能します。

def prompt_list_length(err=None):
    if err:
        print "ERROR: %s" % err
    print "How many things (up to 17) do you want in the list?"
    listlong = raw_input("> ")
    try:
        # See if the list can be converted to an integer,
        # Python will raise an excepton of type 'ValueError'
        # if it can't be converted.
        listlong = int(listlong)
    except ValueError:
        # Couldn't be converted to an integer.
        # Call the function recursively, include error message.
        listlong = prompt_list_length("The value provided wasn't an integer")
    except:
        # Catch any exception that isn't a ValueError... shouldn't hit this.
        # By simply telling it to 'raise', we're telling it to not handle
        # the exception and pass it along.
        raise
    if listlong > 17:
        # Again call it recursively.
        listlong = prompt_list_length("Gotta be a number less than 17, chumpy!")

    return listlong

input = prompt_list_length()
print "Final input value was: %d" % input
于 2012-02-29T03:28:21.457 に答える