ErmahgerdLulz
ErmahgerdLulz

Reputation: 13

"TypeError : not all arguments converted during string formatting" in a Python list

I am writing a recursive function that will print the result of converting a base 10 integer to its equivalent in another base. At line 11 I receive:

TypeError: not all arguments converted during string formatting

Can anyone see what I am doing wrong here and how should I fix it?

list = []

def con2base(integer, base):
    if integer == 0:
        if list == []:
            list.insert(0, 0)
            return 0
        else:
            return 0
    while integer > 0:
        list.insert(0, (integer % base))    <----- This is the offending line
        return con2base(integer / base, base)

print ("Enter number to be converted: ")
integer = raw_input()
print ("Enter base for conversion: ")
base = raw_input()
con2base(integer, base)

print list

Upvotes: 0

Views: 754

Answers (1)

TheSoundDefense
TheSoundDefense

Reputation: 6945

raw_input will always return a string object, and never an actual integer. You need to convert both of them to ints first.

print ("Enter number to be converted: ")
integer = int(raw_input())
print ("Enter base for conversion: ")
base = int(raw_input())
con2base(integer, base)

The reason for the weird error message is that % is an operator that also works on strings; specifically, it's the string format operator. It lets you create one string with "placeholder" elements, which you can fill in at runtime with other strings. So when you get the numbers using raw_input and then try to use %, Python thinks you are trying to do string formatting/substitution.

Upvotes: 4

Related Questions