th0bard
th0bard

Reputation: 107

Why is my function returning nonetype even as I'm returning a value?

I'm making a code for DMOJ challenge 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)

I've tried to use the return command with only the "calde", with "print(calde)", and I'm still getting a nonetype, and if I try to use "return int(calde), I get an error saying that the "int()" command cannot be applied to "NoneType".

Upvotes: 0

Views: 1400

Answers (1)

Achxy_
Achxy_

Reputation: 1201

This happens because the return value of print is always None
To demonstrate this :

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

What you probably meant to do is print the value and then return it, for example :

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

Furthermore, that code can be refactored to this :

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)))

Upvotes: 2

Related Questions