4 2 3 Default Arguments Explained
Key Concepts
Default arguments in Python functions allow you to specify default values for parameters. These values are used if the caller does not provide an argument for that parameter. The key concepts include:
- Defining Default Arguments
- Using Default Arguments
- Order of Parameters
- Overriding Default Arguments
1. Defining Default Arguments
Default arguments are defined in the function signature by assigning a value to the parameter. This value is used if the caller does not provide an argument for that parameter.
Example:
def greet(name="World"): print(f"Hello, {name}!")
2. Using Default Arguments
When a function with default arguments is called without providing values for those parameters, the default values are used.
Example:
greet() # Output: Hello, World! greet("Alice") # Output: Hello, Alice!
3. Order of Parameters
When defining a function with both regular and default arguments, the default arguments must come after the regular arguments. This ensures that the caller can provide values for the regular arguments without ambiguity.
Example:
def greet(greeting, name="World"): print(f"{greeting}, {name}!") greet("Hi") # Output: Hi, World! greet("Hi", "Alice") # Output: Hi, Alice!
4. Overriding Default Arguments
Default arguments can be overridden by providing a value for the parameter when calling the function. This allows for flexibility in function usage.
Example:
def calculate_area(radius, pi=3.14159): return pi * radius ** 2 print(calculate_area(5)) # Output: 78.53975 print(calculate_area(5, 3.14)) # Output: 78.5
Putting It All Together
By understanding and using default arguments effectively, you can create more flexible and user-friendly functions in Python. Default arguments allow you to provide sensible defaults while still allowing for customization when needed.
Example:
def create_profile(name, age=None, city="Unknown"): profile = f"Name: {name}, Age: {age if age else 'Not provided'}, City: {city}" return profile print(create_profile("Alice")) # Output: Name: Alice, Age: Not provided, City: Unknown print(create_profile("Bob", 30)) # Output: Name: Bob, Age: 30, City: Unknown print(create_profile("Charlie", 25, "New York")) # Output: Name: Charlie, Age: 25, City: New York