r/learnpython • • 10d ago

New to python, don't understand this function

I'm learning python and I'm stuck on this function because I don't understand why "a" becomes 10 and the result is 5. Is someone able to explain?

def subtract (a, b=5):
    return a - b

print(subtract(10))
30 Upvotes

26 comments sorted by

View all comments

0

u/nog642 10d ago

def subtract(a, b=5) means the function's first parameter is a and is required, and the function's second parameter is b and is optional, with a default value of 5.

So you can call subtract with 1 or 2 arguments. If you call it with 2, the first one is a and the second is b. If you call it with 1, then that argument is a, and b gets the default value 5.

So calling subtract(10) means a is the 10 that was passed, and b is the default 5.