-2

I am trying to create a program where it takes in a list of numbers and then it will only take the even numbers and print it.

My problem is that I am trying to understand how to give it the list of numbers for it to take in to the parameter.

Here is my code:

def getEvens(NumList):
    NumList = []
    for num in NumList:
        if num % 2 == 0:
            print(num, end = ",")
getEvens(39,94,3,4,5,67) # <--- How can I make this all go to one parameter?
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 3
    Does this answer your question? [Can a variable number of arguments be passed to a function?](https://stackoverflow.com/questions/919680/can-a-variable-number-of-arguments-be-passed-to-a-function) – Brian61354270 Jun 06 '21 at 00:15
  • 2
    The above dupe explains how to do what you want. The simpler, more usable way would just be to pass a list though: `getEvens([39,94,3,4,5,67])`. Also, get rid of `NumList = []`. That will break things. – Carcigenicate Jun 06 '21 at 00:16

2 Answers2

0
def getEvens(NumList):
    for num in NumList:
        if num % 2 == 0:
            print(num, end = ",")

getEvens([39,94,3,4,5,67])

Remove NumList = [] because this just overwrites the parameter with an empty list

wrap the number params in [] to make them into a list when calling the function

Ian Kenney
  • 6,376
  • 1
  • 25
  • 44
0

There is a non-keyword argument called *args which lets you pass several values at a time. More details on args here

def getEvens(*nums):
    for num in nums:
        if num % 2 == 0:
            print(num, end = ",")

getEvens(39,94,3,4,5,67)

You can makes this more simple using filter function

nums = (39,94,3,4,5,67)

getEvens = list(filter(lambda x: x % 2 == 0, nums))

print(','.join(getEvens))
Ghantey
  • 626
  • 2
  • 11
  • 25