-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 对您的问题所评论的那样,您首先需要将您的替换printreturn.

如果分数值得骄傲,你可能想要另一个条件对吧?这是在接收用户输入的分数时:

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_input是 python 中的一个内置函数,可用于获取用户的输入。使用raw_input(), 和int(),我们还可以确保来自用户的输入是一个数字。这是因为int()如果你尝试给它一些不是数字的东西,将会抛出一个特定的错误。它抛出的错误称为 aValueError

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

通过预测这个错误ValueErrorexcept请注意,为了使用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 回答