0

I am trying to create a method which returns the value of three variables added together, with a further condition that that if one of the variables is 13, 14, or between the range 17 -19 inclusive, this particular variable should then count as 0 in the final sum.

I am trying to define a further method to check each number individually so have to write out the same code three times in one method.

My code so far is as follows:

def no_teen_sum(a, b, c):
    fix_teen(a)
    fix_teen(b)
    fix_teen(c)

    return a + b + c


def fix_teen(n):
    if (n == 13 or n == 14) or (n >= 17 and n <= 19):
        n = 0
    return n


print(no_teen_sum(1, 2, 13))

The code is failing to get back the required results and is just adding together a, b and c with no regard for the conditions I have mentioned above. I had thought that calling the checking method 'fix_teen' within the overall method 'no_teen_sum' would combat this but clearly it is being ignored by Python.

How do I achieve what I need to here?

quester
  • 534
  • 5
  • 18
sniffs
  • 1
  • 1

2 Answers2

4

here is my idea for fixing this function

def no_teen_sum(a, b, c):
    new_a = fix_teen(a)
    new_b = fix_teen(b)
    new_c = fix_teen(c)

    return new_a + new_b + new_c

but better solution would be this:

def no_teen_sum(values_list):
    return sum(fix_teen(v) for v in values_list)

advantage of this approach is that you can pass as many values you would like

also for second function you can do this(but only if n is always int):

def fix_teen(n):
    if n in (13, 14, 17, 18, 19):
        n = 0
    return n
quester
  • 534
  • 5
  • 18
  • 2
    The `values_list` version works, but only if you explicitly pass in a list (or any iterable). You can make the argument `*values_list` instead though to make it work with any number of individual arguments passed in. – Robin Zigmond Feb 27 '19 at 10:44
  • true but then code with function with many unnamed arguments are thought to read... maybe let's promote good practices :) – quester Feb 27 '19 at 10:47
  • I get back an error saying that there is 'unsupported operand type(s) for +: 'NoneType' and 'int'' – sniffs Feb 27 '19 at 11:21
0

How about:

def no_teen_sum(a, b, c):
    return fix_teen(a) + fix_teen(b) + fix_teen(c)


def fix_teen(n):
    return 0 if (n == 13 or n == 14) or (17 <= n <= 19) else n


print(no_teen_sum(1, 2, 13))
balderman
  • 22,927
  • 7
  • 34
  • 52