0

The problem is, if I define a function in python with 3 parameters and then I input only 2 parameters, I will get an error.

Can I define the function so if there is one parameter missing (user has given 2 inputs instead of 3), it will use a default value for that missing parameter such as 0?

def sum(a, b, c):
    return a+b+c

If I use:

add = sum(1, 2)
print(add)

It will give me an error. Now I want to define the function so it will add the missing value as 0, but if I give all the 3 values, it will not use 0 as a default value.

martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

3

you can use default parameters:

def my_sum(a, b, c=0):
    return  a + b + c
kederrac
  • 16,819
  • 6
  • 32
  • 55
0

When defining the defining a function if you set a value to a parameter, then you are tellign the function to use that value as default, except a value is specified. This means that by setting a=0,b=0,c=0 AS @Olvin Roght said, you will by default pass a 0 to those parameters (hence not affecting your sum) unless something else is specified.

Example:

def sum(a=0, b=0, c=0):
    return a+b+c

Output:

print(sum(a=1,b=2))
3 #1+2+0
print(sum(a=1,b=2,c=3))
6 #1+2+3
print(sum())
0 #0+0+0
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53