[英]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:我开始尝试 Python,但我不明白我的代码有什么问题......我得到:
... print ("x:%d, prime YES") % (x) ...打印(“x:%d,素数是”)%(x)
TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'类型错误:% 不支持的操作数类型:'NoneType' 和 'int'
Wait -- I've found it.等等——我找到了。 You are using Python 3!您正在使用 Python 3! In which print
is a function.其中print
是一个函数。 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.由于print
返回None
,这会给你带来的错误。
Also, beware -- (x)
is not a tuple containing 1 element, it's simply the value x
.另外,请注意 - (x)
不是包含 1 个元素的元组,它只是值x
。 Use (x,)
for the tuple.使用(x,)
作为元组。
So just move the parens and add a comma:所以只需移动括号并添加一个逗号:
print("x:%d, prime YES" % (x,))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.