【问题标题】:How to fix "TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'"?如何修复“TypeError:+ 的不支持的操作数类型:'NoneType' 和 'str'”?
【发布时间】:2013-02-08 19:17:17
【问题描述】:

我不确定为什么会出现此错误

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

【问题讨论】:

    标签: python python-3.x string input typeerror


    【解决方案1】:

    在 python3 中,print 是一个返回None函数。所以,这行:

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

    你有None + str(count)

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

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

    【讨论】:

      【解决方案2】:

      你的括号放错地方了:

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

      把它移到这里:

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

      或者只使用逗号:

      print("number of donuts:", count)
      

      【讨论】:

      • 非常感谢您的帮助!
      【解决方案3】:

      在 Python 3 中 print 不再是语句。你想做的,

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

      而不是添加到 print() 返回值(即 None)

      【讨论】:

        【解决方案4】:

        现在,使用 python3,您可以使用f-Strings,例如:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-15
          • 1970-01-01
          • 2020-01-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多