Python 类型错误:% 不支持的操作数类型:'NoneType' 和 'int'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22070888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'
提问by peperunas
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)
TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'
... print ("x:%d, prime YES") % (x)
TypeError: %不支持的操作数类型:'NoneType' 和 'int'
采纳答案by RemcoGerlich
Wait -- I've found it. You are using Python 3! In which printis a function. And therefore,
等等——我找到了。您正在使用 Python 3!其中print是一个函数。因此,
print ("x:%d, prime YES") % (x)
actually means
实际上是指
(print ("x:%d, prime YES")) % (x)
And since printreturns 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. Use (x,)for the tuple.
另外,请注意 --(x)不是包含 1 个元素的元组,它只是 value x。使用(x,)的元组。
So just move the parens and add a comma:
所以只需移动括号并添加一个逗号:
print("x:%d, prime YES" % (x,))

