-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
  • 52,115
  • 13
  • 74
  • 94
  • 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) – Brian 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

3 Answers3

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,166
  • 1
  • 24
  • 42
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
  • 524
  • 9
  • 22
-1

One problem I found with this code was the

NumList = []

This resets the number list that the user put in as the parameters, so you are now working with an empty list, removing this line is the first step.

In order to make it one parameter, use a list as the argument, put all the numbers into a list, here is an example:

getEvens(39,94,3,4,5,67)
Dharman
  • 26,923
  • 21
  • 73
  • 125
Samisai
  • 1
  • 1