[英]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".使用 format 方法修改 student_grade function,使其返回短语“X 在考试中收到 Y%”。 For example, student_grade("Reed", 80) should return "Reed received 80% on the exam".
例如,student_grade("Reed", 80) 应该返回“Reed 在考试中获得了 80%”。
I solve this code just like this and I got the result but Coursera shows that is wrong answer why?我像这样解决了这段代码,我得到了结果,但是 Coursera 显示这是错误的答案,为什么?
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这是您的 output:Reed 在考试中获得 80%
Paige received 92% on the exam佩奇在考试中获得 92%
Jesse received 85% on the exam杰西在考试中获得了 85%
Not quite.不完全的。 Check that you're filling in the contents of the student_grade function as requested.
检查您是否按照要求填写了 student_grade function 的内容。
TL;DR: The question is asking you to return the string. TL;DR:问题是要求您返回字符串。 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.为了将值传递给函数,我们使用 arguments。 But what if we want to pass values back?
但是如果我们想把值传回来呢? Say we make a function,
add()
.假设我们制作了一个 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;
如果只是打印结果,那么调用function的代码是拿不到的; 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.这就是返回的来源。返回值是调用代码在调用 function 时得到的值。 To return in Python, we use the
return
statement.要在 Python 中返回,我们使用
return
语句。 A kind of common misconception is that return
itself is a function, and you need to put parentheses aroundt he value being returned.一种常见的误解是,
return
本身就是 function,您需要在要返回的值周围加上括号。 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:后来,如果它愿意,output 它:
print(grade)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.