类型错误:不支持+的操作数类型:“NoneType”和“NoneType”

2024-05-23 13:45:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python 3.5的初级编程知识做了一个有趣的小练习。

def potato_quant(number):
    if number >= 5 and number < 100:
        print("You've got more than 5 potatoes. Making a big meal eh?")
    elif number >= 100 and number < 10000:
        print("You've got more than 100 potatoes! What do you need all those potatoes for?")
    elif number >= 10000 and number < 40000:
        print("You've got more than 10000! Nobody needs that many potatoes!")
    elif number >= 40000:
        print("You've got more than 40000 potatoes. wut.")
    elif number == 0:
        print("No potatoes eh?")
    elif number < 5:
        print("You've got less than five potatoes. A few potatoes go a long way.")
    else:
        return 0
 def potato_type(variety):
     if variety == "Red":
        print("You have chosen Red potatoes.")
     elif variety == "Sweet":
        print("You have chosen the tasty sweet potato.")
     elif variety == "Russet":
          print("You've got the tasty average joe potatoe!")
     else:
          print("Nice potato!")

print(potato_quant(15000) + potato_type("Sweet"))

代码的目标是根据我的选择输入两个值并获取两个字符串。但是,当我运行代码时,我会得到一个错误:

TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'

我是个初学者,所以不管我看了多少遍,我都看不出哪里不对劲。任何帮助都将非常感谢,主要是为了将来使用。


Tags: andyounumberdefmoretypevepotato
2条回答

print替换为return,您就可以:

def potato_quant(number):
    if number >= 5 and number < 100:
        return("You've got more than 5 potatoes. Making a big meal eh?")
    elif number >= 100 and number < 10000:
        return("You've got more than 100 potatoes! What do you need all those potatoes for?")
    elif number >= 10000 and number < 40000:
        return("You've got more than 10000! Nobody needs that many potatoes!")
    elif number >= 40000:
        return("You've got more than 40000 potatoes. wut.")
    elif number == 0:
        return("No potatoes eh?")
    elif number < 5:
        return("You've got less than five potatoes. A few potatoes go a long way.")
    else:
        return '0'

def potato_type(variety):
    if variety == "Red":
        return("You have chosen Red potatoes.")
    elif variety == "Sweet":
        return("You have chosen the tasty sweet potato.")
    elif variety == "Russet":
        return("You've got the tasty average joe potatoe!")
    else:
        return("Nice potato!")

print(potato_quant(15000) + potato_type("Sweet"))

在第print(potato_quant(15000) + potato_type("Sweet"))行中,您调用的函数potato_quant&;potato_type必须返回要打印的值。

因为您的函数有print而不是return,所以它们返回None,并且操作数+None上未定义。因此出现错误消息。

如果potato_quant返回0,它将提高TypeError: unsupported operand type(s) for +: 'int' and 'str'。所以我把return 0替换为replace '0'来解决这个问题。

由于potato_quantpotato_type已经进行了打印,因此不需要在print调用内调用它们。

您得到的错误是因为函数除了在else中没有return语句,所以默认情况下它返回None

你真正需要做的就是改变最后一行:

print(potato_quant(15000) + potato_type("Sweet"))

potato_quant(1500)
potato_type("Sweet")

相关问题 更多 >