peperunas
peperunas

Reputation: 438

TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'

def prime(x):
    if (x == 0 or x % 2 == 0):
        return 0
    elif (x == 1):  
        return 1
    else:
        for y in range(x-1,0,-1):
            if (x % y == 0):
                return 0
            else:
                pass
        if (y == 1):
            return 1

for x in range(1,20):
    if (prime(x)):
        print ("x:%d, prime YES") % (x)
    else:
        print ("x:%d, prime NO") % (x)

I'm starting experimenting Python and I can't understand what's wrong with my code... I'm getting:

... print ("x:%d, prime YES") % (x)
TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'

Upvotes: 4

Views: 33031

Answers (1)

RemcoGerlich
RemcoGerlich

Reputation: 31270

Wait -- I've found it. You are using Python 3! In which print is a function. And therefore,

print ("x:%d, prime YES") % (x)

actually means

(print ("x:%d, prime YES")) % (x)

And since print returns None, that gives you the error you are getting.

Also, beware -- (x) is not a tuple containing 1 element, it's simply the value x. Use (x,) for the tuple.

So just move the parens and add a comma:

print("x:%d, prime YES" % (x,))

Upvotes: 18

Related Questions