-2
def even_number(*args):
    for even in args:
        if even%2==0:
            even
            print(list(str(even)),end='')

I want to print the output in a list as [8,6,4], but rather it prints it out as [8],[6],[4]. If I put out the last print statement and just print(even), it obviously doesn't list out the output.

zwer
  • 24,943
  • 3
  • 48
  • 66
YAsh rAj
  • 85
  • 1
  • 6
  • 1
    Rather than telling people to ignore the indentation, would you mind fixing it? – ayhan Apr 04 '18 at 13:48
  • The indention got odd while typing it out here. It’s the usual in the IDE. – YAsh rAj Apr 04 '18 at 13:49
  • Also, do you think that a title like "Python 3, *args" is very specific to your problem and descriptive? I have seen that you tend to use short titles which give no clue regarding the actual problem. This is not good, IMHO. – nbro Apr 04 '18 at 13:49
  • I added the rest which makes it more descriptive now, I think. Thank you for the suggestions though. – YAsh rAj Apr 04 '18 at 13:51

5 Answers5

0

Your problem is that you print every time you enter in your if. Instead, you want to add your number to a list every time you enter the loop and then print it :

def even_number(*args):
     my_list = list()
     for even in args:
        if even%2==0:
            my_list.append(even)
     print(my_list)

EDIT : The others answer are correct by the way. It's better to use the comprehension list. I don't remove my answer so you get to understand what your mistake was.

T.Nel
  • 1,540
  • 2
  • 18
  • 34
0
def even_number(*args):
  print([i for i in args if i % 2 == 0])
shahaf
  • 4,750
  • 2
  • 29
  • 32
0

You need to collect the result before printing it if you want to print it as a list, i.e.:

def even_number(*args):
    evens = [a for a in args if a % 2 == 0]
    print(evens)
# test:
even_number(*range(10))  # [0, 2, 4, 6, 8]
zwer
  • 24,943
  • 3
  • 48
  • 66
0

Just use a list comprehension with:

def even_number(*args):
    even = [n for n in args if n % 2 == 0]
    print(even)
tombarti
  • 426
  • 2
  • 8
0

Simple code

def even_number(*args):
    result = []
    for even in args:
        if even % 2 == 0:
            result.append(even)
    return result

with comprehension list

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

for to use function even_number

print even_number(range(10))
Fred
  • 1,011
  • 1
  • 10
  • 36