-4

答えてくれてありがとう。このコードはこれでうまく機能します。

def rate_score(selection):
    if selection < 1000:
        return "Nothing to be proud of!"

    elif selection >= 1000 and selection < 10000:
        return "Not bad."

    elif selection >= 10000:
        return "Nice!"

def main():
    print "Let's rate your score."
    while True:
        selection = int(raw_input('Please enter your score: '))
        break
    print 'You entered [ %s ] as your score' % selection
    score = rate_score(selection)
    print score

main()

ただし、rate_score(selection) のパラメーターをデフォルトとして 0 に設定し、関数に値を渡さない rate_score(selection) への呼び出しを追加する必要もあります。コードを次のように修正しました。

def rate_score(selection):
    if selection < 1000:
        return "Nothing to be proud of!"

    elif selection >= 1000 and selection < 10000:
        return "Not bad."

    elif selection >= 10000:
        return "Nice!"

    else:
        selection = 0

selection = int(raw_input("Enter your score. "))

score = rate_score(selection)
print score

少なくとも、デフォルトのパラメーターが 0 になるように設定しましたか? そうでない場合は、rate_score() のデフォルト パラメータに変更するにはどうすればよいですか? また、raw_inputのために何も入力しないとエラーが発生することを考慮して、rate_scoreに値を渡さないようにする方法もわかりません。

4

2 に答える 2

3

「そして文字列を返す」 - それがreturnキーワードの目的です。

def rate_score(score):
    if score < 1000:
        return "Nothing to be proud of."
于 2013-10-06T15:48:15.420 に答える
0

Lasse V. Karlsen があなたの質問にコメントしたように、最初にあなたprintを. に置き換える必要がありますreturn

スコアが自慢できるものなら、おそらく別の条件が必要ですよね?これは、ユーザーからの入力としてスコアを受け取っている間です。

def rate_score(selection):
    if selection < 1000:
        return "Nothing to be proud of!"
    else:
        return "Now that's something to be proud of!"

def main():
    print "# rate_score program #"
    while True:
        try:
            selection = int(raw_input('Please enter your score: '))
        except ValueError:
            print 'The value you entered does not appear to be a number !'
            continue
        print 'You entered [ %s ] as your score' % selection
        response = rate_score(selection) # Now the function rate_score returns the response
        print response # Now we can print the response rate_score() returned

main()

raw_inputpython の組み込み関数であり、ユーザーからの入力を取得するために使用できます。raw_input()、およびを使用int()して、ユーザーからの入力が数値であることを確認することもできます。これはint()、数値ではないものを指定しようとすると、特定のエラーがスローされるためです。スローされるエラーは a と呼ばれますValueError

>>> int('notanumber')
ValueError: invalid literal for int() with base 10: 'notanumber'

このエラー ( ValueError) を予期してステートメントでキャッチすることによりexcept、入力が数値として評価されなかったとプログラムが判断したときにユーザーに通知できます。ステートメントでエラーをキャッチするには、exceptエラーをスローする式をtryステートメントで評価する必要があることに注意してください。

try:
    # begin code which we know will throw the `ValueError`
    selection = int(raw_input('Please enter your score: '))
except ValueError:
    # what to do if the `ValueError` occurs?
    # tell the user that what they entered doesn't appear to be a number
    print 'The value you entered does not appear to be a number !'
    continue
于 2013-10-06T15:58:56.957 に答える