Home > Software design >  How to find a even number using a for loop contains n1 to n2
How to find a even number using a for loop contains n1 to n2

Time:12-03

Am not getting it right. Why do I get an AssertionError for my function even_numbers?

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

CodePudding user response:

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?)

Second, as noted in comments, the function filters adequately even numbers, but then prints them, and doesn't return anything.

You would like to return a list of all even numbers, so you need to collect them in a list, then return that.

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

CodePudding user response:

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.

Also, why you added a 0 to your range limit? 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.

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 ;)

  • Related