为什么我的函数在返回值时返回 nonetype?



我正在为DMOJ挑战CCC’06 J1:编写代码

b = [
["1", 461],
["2", 431],
["3", 420],
["4", 0]
]
dr = [
["1", 130],
["2", 160],
["3", 118],
["4", 0]
]
s = [
["1", 100],
["2", 57],
["3", 70],
["4", 0]
]
de = [
["1", 167],
["2", 266],
["3", 75],
["4", 0]
]
#Lists with order types
#b = burgers, dr = drinks, s = side orders, de = desserts

brg = int(input())
sord = int(input())
drk = int(input())
dess = int(input())
def cbrg():
for i in range(brg):
calb = b[brg-1][1]
return print(calb)
def csord():
for i in range(sord):
cals = s[sord-1][1]
return print(cals)
def cdrk():
for i in range(drk):
caldr = dr[drk-1][1]
return print(caldr)
def cdess():
for i in range(dess):
calde = de[dess-1][1]
return print(calde)

我已经尝试过使用return命令;calde";,用";print(calde)";,并且我仍然得到一个nonetype,并且如果我尝试使用";return int(calde),我得到一个错误,说";int()"命令不能应用于";NoneType";。

之所以会发生这种情况,是因为print的返回值始终为None
为了证明这一点:

>>> foo = print("Evidence!")
Evidence!
>>> print(foo)
None
>>> type(foo)
<class 'NoneType'>

您可能想做的是打印值并,然后返回它,例如:

>>> def print_and_return(x):
...     print(x)
...     return x
...
>>> some = print_and_return(10)
10
>>> some
10

此外,该代码可以重构为:

ITEMS = [[461, 431, 420, 0], [100, 57, 70, 0], [130, 160, 118, 0], [167, 266, 75, 0]]

def get_calorie_count(orders):
return sum(item[order - 1] for item, order in zip(ITEMS, orders))

print("Your total Calorie count is", get_calorie_count(int(input()) for _ in range(4)))

相关内容

  • 没有找到相关文章

最新更新