我使用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'
我是一个非常初学者,所以无论我多看多少,我都看不出有什么不对劲。任何帮助都将非常受欢迎,主要是为了将来使用。
答案 0 :(得分: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
&amp; potato_type
必须返回要打印的值。
由于您的函数有print
而不是return
,因此它们会返回None
,并且+
上的操作数None
未定义。因此错误信息。
如果potato_quant
返回0
,则会提升TypeError: unsupported operand type(s) for +: 'int' and 'str'
。因此,我将return 0
替换为replace '0'
以解决此问题。
答案 1 :(得分:0)
由于potato_quant
和potato_type
已经进行了打印,因此您无需在print
来电中拨打电话。
您收到的错误是因为除return
之外的函数没有else
声明,因此默认情况下它会返回None
你真正需要做的就是改变最后一行:
print(potato_quant(15000) + potato_type("Sweet"))
到
potato_quant(1500)
potato_type("Sweet")