简体   繁体   中英

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'

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,))

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