python TypeError not all arguments converted during string formatting

Question:

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

Asked By: farhan chowdhry

||

Answers:

x is a string, therefore the % resolves to string interpolation instead of modulo. Use int(x) % 2 == 0.

The error is raised, because 2 is the string formatting argument, but the string does not contain a matching amount of format specifiers.

Answered By: code_onkel

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

Answered By: Moses Koledoye
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.