2

Python function that adds two numbers: a and b. Return a + 1, if no value is provided for b.

def sum(a,b):
    if b is None:
        return a + 1
    else:
        return a + b
print(sum(3,2))

I tried print(sum(2))

Then --> TypeError: sum() missing 1 required positional argument: 'b'

b == None? b is None? ... How can i fix it?

Thank you in advance!!

Suwan Wang
  • 83
  • 1
  • 8
  • Possible duplicate of [How do I create a Python function with optional arguments?](https://stackoverflow.com/questions/9539921/how-do-i-create-a-python-function-with-optional-arguments) – takendarkk Oct 23 '18 at 20:01

3 Answers3

4

You can supply a default value of None to b. Also, as noted by @vash_the_stampede, you should not use sum because that is a built-in function. Change to something like my_sum

def my_sum(a,b=None):
    if b is None:
        return a + 1
    else:
        return a + b


>>> print(my_sum(2))
3
sacuL
  • 49,704
  • 8
  • 81
  • 106
  • 1
    Shouldn't we alter the function name from `sum` to a non built in function variable name – vash_the_stampede Oct 23 '18 at 20:03
  • @sacul Thank you!! But I don't really understand the logic of "not b" in this case. "return a + 1 if b is None else a + b" makes sense to me. If b has a default value of None, then "not b" means "not None", right? so b has a value? If b has a value, it shouldn't return a + 1. Although the code runs perfectly but i am very confused. Could you explain a bit more? Thank you!! – Suwan Wang Oct 23 '18 at 20:24
  • Yes, I actually removed that and changed it back to `if b is None`, because `if not b` would still be satisfied otherwise. Sorry for the confusion! – sacuL Oct 23 '18 at 20:27
  • :) Now I understand much better!! Thank you – Suwan Wang Oct 23 '18 at 20:36
4

You need to have a default in your function signature.

def my_sum(a, b=None):
    return a + 1 if b is None else a + b

I also changed the name of the function to my_sum since sum is a builtin, and the condition to b is None because not b would be true if b = 0 as well.

mVChr
  • 49,587
  • 11
  • 107
  • 104
4

The shortest version:

def sum_ab(a, b=1):
    return a + b
Marek
  • 862
  • 7
  • 19