简体   繁体   中英

Python: TypeError - not all arguments converted during string formatting

I'm writing a basic Python script, the code of which is as followsdef is_prime(n):

def is_prime(n):
    i = 2
    while i<n:
        if(n%i == 0):
            return False
        i+=1
    return True

def truncable(num):
    li = []
    x = str(num)
    if(is_prime(num)):
        n = len(x)
        check = ""
        i = 1
        while(i<n):
            if(is_prime(x[i:])):
                check = "True"
            else:
                check = "False"
                break
        if(check == "True"):
            li.append(num)

print truncable(3797)   

However, after running this script, I get the following error:

TypeError: not all arguments converted during string formatting

What's wrong with my code?

This happens when n in the expression n%i is a string, not an integer. You made x a string, then passed it to is_prime() :

>>> is_prime('5')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in is_prime
TypeError: not all arguments converted during string formatting
>>> is_prime(5)
True

Pass integers to is_prime() instead:

is_prime(int(x[i:]))

The % operator on a string is used for string formatting operations .

You appear to have forgotten to return anything from truncable() ; perhaps you wanted to add:

return li

at the end?

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