简体   繁体   中英

“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

raw_input will always return a string object, and never an actual integer. You need to convert both of them to int s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM