Search code examples
pythontypeerror

python TypeError not all arguments converted during string formatting


The program is meant to find the odd number in the string by checking if the number can be divided by 2 without a remainder, here is the code:

def iq_test(numbers): 
    for x in numbers.split():
       if x % 2 != 0:
          return x 

iq_test("1 2 3 4 5")

Here is the error i get when i run the code:

Traceback (most recent call last):
File "python", line 6, in <module>
File "python", line 3, in iq_test
TypeError: not all arguments converted during string formatting

Any help would be appreciated


Solution

  • When you use % (or more verbose operator.mod) on string literals, you're attempting to format:

    >>> a = 'name'
    >>> ('%s' % a) == 'name'
    True
    

    But you intend to use this on int, so you need to cast your string literals to integer:

    if int(x) % 2 != 0
    

    Then mod will attempt to find the modulus instead of attempting to format.

    However, your function will return as soon as it finds the first odd number. If you intend to find all the odd numbers and not just the first, you can accumulate the odd numbers in a list and return the joined list:

    def iq_test(numbers): 
        lst = []
        for x in numbers.split():
           if int(x) % 2 != 0:
               lst.append(x) 
    
        return ' '.join(lst)
    
    iq_test("1 2 3 4 5")
    # "1 3 5"
    

    Another sleek alternative will be to try out generator functions/expressions and yield