Let us get an overview of different types of Function Parameters and Arguments supported by Python.
-
Parameter is a variable in the declaration of the function. An argument is the actual value of this variable that gets passed to the function.
-
However, in some cases, these two terms are used interchangeably.
-
In Python, parameters can be objects or even functions. We can pass named functions or lambda functions as arguments. We will talk about these details later.
-
Here are different types of parameters or arguments:
- Parameters with Default Values
- Varying arguments
- Keyword arguments
- Varying Keyword arguments
-
We can pass arguments to a function by parameter position or name. If you use the name, you can pass arguments in any order.
-
You can only specify parameters with default values after mandatory parameters.
def get_commission_amount(sales_amount=1000, commission_pct)
is syntactically wrong and throws an error.
Tasks
Let us perform a few tasks to understand more about parameters and arguments with and without default values.
-
Checking whether phone numbers of a given employee are valid -
get_invalid_phone_count
- Function should take 2 arguments,
employee_id
andphone_numbers
(list) - Check whether each phone number has 10 digits.
- Return
employee_id
and the number of phone numbers with less than 10 digits
- Function should take 2 arguments,
-
Get commission amount by passing sales amount and commission percentage. However, if the commission percentage is not passed from the caller, then the default percentage should be 10.
def get_invalid_phone_count(employee_id, phone_numbers):
invalid_count = 0
for phone_number in phone_numbers:
if len(phone_number) != 10:
invalid_count += 1
return employee_id, invalid_count
s = 'Employee {employee_id} has {invalid_count} invalid phones'
employee_id, invalid_count = get_invalid_phone_count(1, ['1234', '1234567890'])
print(s.format(employee_id=employee_id, invalid_count=invalid_count))
def get_commission_amount(sales_amount, commission_pct=10):
"""Function to compute commission amount. Commission_pct should be passed as percent notation (e.g., 20%)
20% using percent notation is equal to 0.20 in decimal notation.
"""
if commission_pct and commission_pct > 100:
print('Invalid Commission Percentage, greater than 100')
return
commission_amount = sales_amount * (commission_pct / 100) if commission_pct else 0
return commission_amount
# Arguments by position
get_commission_amount(1000, 5)
# Will take commission_pct default value
get_commission_amount(1000)
get_commission_amount(1000, None)
get_commission_amount(1000, 150)
# Arguments by name
get_commission_amount(commission_pct=18, sales_amount=1500)
Summary of the main points discussed in the article. Encourage the reader to practice or engage with the community for further learning.