简体   繁体   中英

I solve a code in Coursera using this method and it worked but they didn't accept it?

Modify the student_grade function using the format method, so that it returns the phrase "X received Y% on the exam". For example, student_grade("Reed", 80) should return "Reed received 80% on the exam".

I solve this code just like this and I got the result but Coursera shows that is wrong answer why?

def student_grade(name, grade):
    print("{name} received {grade}% on the exam".format(name=name,grade=grade))
    return ""

Here is your output: Reed received 80% on the exam

Paige received 92% on the exam

Jesse received 85% on the exam

Not quite. Check that you're filling in the contents of the student_grade function as requested.

TL;DR: The question is asking you to return the string. What you are doing is printing it. Instead, do this:

def student_grade(name, grade):
    return "{name} received {grade}% on the exam".format(name=name,grade=grade)

In order to pass values to functions, we use arguments. But what if we want to pass values back? Say we make a function, add() . It takes two numbers and wants to give the calling code their sum. If it just prints the result, the code that calls the function can't get it; printing is just a way of displaying things to the user.

That's where returns come in. A return value is what the calling code gets when it calls the function. To return in Python, we use the return statement. A kind of common misconception is that return itself is a function, and you need to put parentheses aroundt he value being returned. That is not the case. Thus, instead of printing the value, you should just return it, like so:

def student_grade(name, grade):
    return "{name} received {grade}% on the exam".format(name=name,grade=grade)

Then the calling code can do things with the return value, like store it in a variable:

grade = student_grade("Mark", 97)

And later, if it wants to, output it:

print(grade)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM