-2
def myfunc(*args):
    for x in args:
        if x% 2== 0:
            return x
        else:
            pass

I wanted to know why this code is returning only one value.

halfer
  • 19,471
  • 17
  • 87
  • 173
Anonymous
  • 1
  • 1

3 Answers3

0

You can use a list comprehension which is the simplest, shortest and most Pythonic:

def myfunc(*args):
    return [x for x in args if x % 2 == 0]

Or, sticking with your loop approach, you have to collect the even ones, not just return the first. You can also omit the else: pass as it does nothing:

def myfunc(*args):
    even = []
    for x in args:
        if x % 2 == 0:
            even.append(x)
    return even
user2390182
  • 67,685
  • 6
  • 55
  • 77
0

I wanted to know why this code is returning only one value

Because that's what you're asking it to do. return immediately returns from the function with whatever value you gave it. Since you return x as soon as you encounter an even parameter, that's what the function returns: the first even parameter.

If you want more than one, you need to either accumulate your evens into a structure (e.g. a list) or create a generator function, which can yield multiple values rather than return immediately with a single value.

halfer
  • 19,471
  • 17
  • 87
  • 173
Masklinn
  • 23,560
  • 2
  • 21
  • 39
0

Beacuse when you got the first even number, you 'return' it. If you want to get every even number, store it to a list during the loop, and return the list after the loop.

Aaron
  • 129
  • 1
  • 7