0

I'm trying to pass my function the list IQ, however it only returns "even" (the first element of the list) and not every single element of the list. When I define my if and else statements with print instead of return I seem to get the output I desire however I dont get why the code below only gives me the output for the first element of the list

IQ = [132, 92, 75, 97, 118]
def odd_or_even(*args):
    for x in IQ:
     if x % 2 == 0:
        return "Even"
     else:
        return "Odd"

print(odd_or_even(IQ))
costaparas
  • 5,047
  • 11
  • 16
  • 26
atyahoo
  • 41
  • 5

2 Answers2

0

As soon as a function hits a return, it will do just that -- it will return from the function. What this means here is that only the first value in the list is ever looked at.

Merely printing the values in the loop avoids this. However, if you want to return the result from the function, you need to build up the information during the loop and at the end - once the loop has finished - you can return the overall result.

Below, is an example way to do this by appending the parity to the list res and appending to it in each iteration.

IQ = [132, 92, 75, 97, 118]

def odd_or_even(*args):
    res = []
    for x in args:
        if x % 2 == 0:
            res.append('Even')
        else:
            res.append('Odd')
    return res

res = odd_or_even(*IQ)
for i, parity in enumerate(res):
    print(f'{IQ[i]} is {parity}')

As a side note, your original code also ignored its input argument completely. It uses IQ rather than args. Had you not used IQ, you would've also noticed the other problem; which is the way you passed in the list IQ - you were missing the necessary * to unpack the list. Read more about how args and kwargs work in this post.

costaparas
  • 5,047
  • 11
  • 16
  • 26
0

Can be 1 liner:

In[1]: IQ = [132, 92, 75, 97, 118]
In[2]: list(map(lambda x: "Even" if x % 2 == 0 else "Odd", IQ))
Out[1]: ['Even', 'Even', 'Odd', 'Odd', 'Even']
4d61726b
  • 427
  • 5
  • 26