[英]How to find a even number using a for loop contains n1 to n2
Am not getting it right.我没有做对。 Why do I get an AssertionError for my function even_numbers?
为什么我的 function even_numbers 会出现 AssertionError?
def even_numbers(n1, n2):
(n1, n2) = [-2, 4]
for num in range(n1, n2 + 0):
if num % 2 == 0:
print(num, end = " ")
n1, n2 = [-2, 4]
assert even_numbers(-2, 4) == [-2, 0, 2]
---------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-19-6544d23ef931> in <module>
1 # Q6 Test Cases
----> 2 assert even_numbers(-2, 4) == [-2, 0, 2]
AssertionError
There are a few mistakes in the code.代码中有一些错误。
First, the function overrides the arguments n1, n2
by assigning [-2, 4]
(perhaps a leftover of some debugging?)首先,function 通过分配
[-2, 4]
覆盖 arguments n1, n2
(也许是一些调试的剩余部分?)
Second, as noted in comments, the function filters adequately even numbers, but then prints them, and doesn't return anything.其次,如评论中所述,function 充分过滤偶数,然后打印它们,并且不返回任何内容。
You would like to return a list
of all even numbers, so you need to collect them in a list, then return that.您想返回所有偶数的
list
,因此您需要将它们收集到一个列表中,然后返回。
You can just restructure your code as follow:您可以按如下方式重组您的代码:
def even_numbers(n1, n2):
return [num for num in range(n1, n2) if num % 2 == 0]
>>> even_numbers(-2, 4)
[-2, 0, 2]
assert even_numbers(-2, 4) == [-2, 0, 2]
Note how this is the same code as yours, and even in the same order, but turned into a list comprehension.请注意,这与您的代码如何相同,甚至顺序相同,但变成了列表理解。
You can also keep the code even closer to your original:您还可以使代码更接近原始代码:
def even_numbers(n1, n2):
res = []
for num in range(n1, n2):
if num % 2 == 0:
res.append(num)
return res
What I first notice is that you are not returning anything from the code.我首先注意到的是您没有从代码中返回任何内容。 So, as you want to return a list, you need to have one and append the values to it.
所以,当你想返回一个列表时,你需要有一个和 append 的值给它。
Also, why you added a +0 to your range limit?另外,为什么您在范围限制中添加了+0 ? The value will be the same.
值将相同。 What you may want to do is subtract 1 because range will go from -2 to 3 if you don't do it.
您可能想要做的是减去 1,因为如果您不这样做,go 的范围将从 -2 到 3。
You can do this (tried to make it simple so you understand everything in the code):您可以这样做(试图使其简单,以便您理解代码中的所有内容):
def even_numbers(n1, n2):
even_numbers_list = []
for number in range(n1, n2-1):
if number % 2 == 0:
even_numbers_list.append(number)
return even_numbers_list
>>> even_numbers(-2, 4)
[-2, 0, 2]
Also I advice you to add some logs (or prints) so you can understand better what are the errors of your code.此外,我建议您添加一些日志(或打印),以便您更好地了解代码的错误。 Any question just ask;)
任何问题都可以问;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.