Course Content
Python Functions Tutorial
Python Functions Tutorial
Combination of Positional and Optional Arguments
Consider a function designed to calculate the total cost of smartphones, allowing you to specify various attributes during both initialization and function invocation.
def calculate_smartphone_cost(model, price, quantity=1, discount=0): total_cost = price * quantity discount_amount = total_cost * (discount / 100) discounted_cost = total_cost - discount_amount print(f"Model: {model}") print(f"Unit price: ${price}") print(f"Quantity: {quantity}") print(f"Total cost before discount: ${total_cost}") if discount > 0: print(f"Discount: {discount}%") print(f"Discount amount: ${discount_amount}") print(f"Discounted cost: ${discounted_cost}") else: print("No discount applied.") print(f"Final cost: ${discounted_cost}") print() # Examples of using the function calculate_smartphone_cost("iPhone 13", 1099, 2) calculate_smartphone_cost("Samsung Galaxy S21", 999, 1, 10) calculate_smartphone_cost("Google Pixel 6", 799, quantity=3, discount=5)
Rules for Specifying Arguments
Positional Arguments
Positional arguments must be specified in the order they are defined in the function declaration. For example, in the function calculate_smartphone_cost
, model
and price
are mandatory positional arguments.
Optional (Named) Arguments
Optional arguments can be specified either positionally or using named parameters. In the example, quantity
and discount
are optional arguments with default values that can be altered using named parameters during function invocation.
Default Values
If an optional argument is not specified during function call, its default value will be used. For instance, in the calculate_smartphone_cost
function, if quantity
and discount
are not provided, they automatically take the values 1 and 0, respectively.
Named Parameters
Named parameters allow precise specification of values for optional arguments and determine their order of appearance. This enhances code clarity and readability, especially when dealing with multiple optional parameters.
This example and the rules for specifying arguments illustrate how to effectively use a combination of positional and named (optional) arguments to create functions that offer flexibility and ease of use, while maintaining code clarity and expected behavior.
Thanks for your feedback!