如何修复“TypeError: 不支持的操作数类型用于 +: 'NoneType' 和 'str'”?

20 投票
4 回答
127579 浏览
提问于 2025-04-17 16:50

我不太明白为什么会出现这个错误

count=int(input ("How many donuts do you have?"))
if count <= 10:
    print ("number of donuts: " ) +str(count)
else:
    print ("Number of donuts: many")

4 个回答

2

现在,在Python 3中,你可以使用 f-Strings 这种方式来格式化字符串,像这样:

print(f"number of donuts: {count}")
9

你的括号放错地方了:

print ("number of donuts: " ) +str(count)
                            ^

把它移动到这里:

print ("number of donuts: " + str(count))
                                        ^

或者直接用逗号:

print("number of donuts:", count)
27

在Python3中,print是一个函数,它的返回值是None。所以,这一行:

print ("number of donuts: " ) +str(count)

你实际上是在做None + str(count)

你可能想要的是使用字符串格式化:

print ("Number of donuts: {}".format(count))

撰写回答