0

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.