MacSuperior
MacSuperior

Reputation: 27

Why is my Python code returning a TypeError?

I'm want a function that checks a string with numbers for odd ones. I want it to print out the position of the odd number(s), but line 4 gives 'TypeError: not all arguments converted during string formatting'. How do i fix this? Code below:

def IQ_test(string):
    numbers = string.split()
    for x in numbers:
        if x % 2 != 0:
            print(numbers.index(x))
IQ_test("1 4 7 5 2")

Upvotes: 0

Views: 69

Answers (3)

Gabio
Gabio

Reputation: 9494

As others already mentioned in this thread, you didn't convert the elements in numbers list into int type.

But I would like to highlight a possible bug in your logic:

Using numbers.index(x) you will find the first occurrence of element x in your list so if the same number repeats more than once, you will get always the first index.

If this is not the desired behavior, you can do:

for index, x in enumerate(numbers):
     if int(x) % 2 != 0:
         print(index)

Upvotes: 0

timhu
timhu

Reputation: 98

use int() to convert the chars into int type:

def IQ_test(string):
    numbers = string.split()
    for x in numbers:
        if int(x) % 2 != 0:
            print(numbers.index(x))
            
IQ_test("1 4 7 5 2")

Upvotes: 4

Ali
Ali

Reputation: 421

use it :

def IQ_test(string):
    numbers = string.split(' ')
    for x in numbers:
        if int(x) % 2 != 0:
            print(numbers.index(x))
IQ_test("1 4 7 5 2")

Upvotes: 0

Related Questions