Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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'

like image 314
peperunas Avatar asked Dec 03 '22 20:12

peperunas


1 Answers

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,))
like image 119
RemcoGerlich Avatar answered Dec 05 '22 09:12

RemcoGerlich