Optional Function Parameters in Python
Function parameters can be made optional. To do this, parameters need to be given default values. Let's see how this is done. Let's assume we have the following function:
def func(num1, num2):
return num1 + num2
print(func(1, 2)) # 3
Let's make the second parameter default to 2
:
def func(num1, num2=2):
return num1 + num2
Let's check how our function works with only the first parameter:
print(func(1)) # 3
Even though the second number is an optional parameter, you can still set a value for it when calling the function:
print(func(2, 4)) # 6
Given a function:
def func(num=5):
return num * 2
This function is called as follows:
print(func(2))
print(func(10))
print(func())
Tell what the result of each function call will be.
Given a function:
def func(num1=1, num2=3):
return num2 - num1
This function is called as follows:
print(func(6, 10))
print(func(5))
print(func())
Tell what the result of each function call will be.