[英]Kinda new to Python Programming and was attempting a question. I just don't know why this error keeps popping up. Really doesn't make sense to me
This was the question: Create a function named add_greetings()
which takes a list of strings named names as a parameter.这就是问题所在:创建一个名为
add_greetings()
的 function,它将名为名称的字符串列表作为参数。
In the function, create an empty list that will contain each greeting.在 function 中,创建一个包含每个问候语的空列表。 Add the string
"Hello, "
in front of each name in names and append the greeting to the list.在名称中的每个名称前添加字符串
"Hello, "
,并在列表中添加问候语 append。
Return the new list containing the greetings.返回包含问候语的新列表。
Quite a basic question but I accidentally initialized the new list outside the function like this:相当基本的问题,但我不小心初始化了 function 之外的新列表,如下所示:
new_lst = []
def add_greetings(names):
for name in names:
name = "Hello, " + name
new_lst.append(name)
return new_lst
print(add_greetings(["Owen", "Max", "Sophie"]))
This was a question on Codecademy and it gave me this error:这是 Codecademy 上的一个问题,它给了我这个错误:
add_greetings(["Owen", "Max", "Sophie"])
should have returned ['Hello, Owen', 'Hello, Max', 'Hello, Sophie']
, and it returned ['Hello, Owen', 'Hello, Max', 'Hello, Sophie', 'Hello, Owen', 'Hello, Owen', 'Hello, Max', 'Hello, Sophie']
add_greetings(["Owen", "Max", "Sophie"])
应该返回['Hello, Owen', 'Hello, Max', 'Hello, Sophie']
,它返回['Hello, Owen', 'Hello, Max', 'Hello, Sophie', 'Hello, Owen', 'Hello, Owen', 'Hello, Max', 'Hello, Sophie']
Why is this the case?为什么会这样? Tried it on the Python IDE, and it gave me the expected correct answer.
在 Python IDE 上尝试过,它给了我预期的正确答案。
You should try instantiating the new_list inside the function:您应该尝试在 function 中实例化 new_list:
def add_greetings(names):
new_lst = []
for name in names:
name = "Hello, " + name
new_lst.append(name)
return new_lst
print(add_greetings(["Owen", "Max", "Sophie"]))
What ends up happening when Codeacademy tests it is they will run more than one test case.当 Codeacademy 测试时最终会发生什么,它们将运行多个测试用例。 When you run your method more than once, it will continue appending to the same list over and over again, and will therefore return the wrong result.
当你多次运行你的方法时,它会一遍又一遍地追加到同一个列表中,因此会返回错误的结果。 This can be mitigated by putting the list initialization inside the function itself, so you start fresh each time.
这可以通过将列表初始化放入function 本身来缓解,因此您每次都重新开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.