0

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?

2
  • 1
    Note that if you'd been using Python 3, you would have gotten a much more helpful error message: TypeError: unorderable types: int() < str() which would have pointed out the underlying problem immediately. Commented Apr 19, 2014 at 15:47
  • 1
    Note that the print will result in None, since you aren't returning anything from truncable. Commented Apr 19, 2014 at 15:47

1 Answer 1

6

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?

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.