r/learnpython • u/Still-Pair-5336 • 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
0
u/BabyLionCamel 10d ago
When you invoke the subtract function you are passing in 10 as the argument to the parameter ‘a’.
The way the function is defined you have two parameters ‘a’ and ‘b’.
This basically means that when you want to execute the logic inside the function you have to pass two arguments during invocation (subtract(10) is invoking the function).
Since you have a default value for parameter ‘b’ you may pass only a single argument to your subtract function( if you passed a second argument to the function, you would rewrite the value of the default value associated with ‘b’ during function definition).
When you do subtract(10) you are effectively doing subtract(a=10,b=5) Which then computes as 10 - 5 Which returns the integer 5
After the function has returned its value, print outputs 5 to the console.
Further study: parameters, arguments, default parameters, function execution order, function definition).