w3resource

What are the default arguments in a function? What is the best way to use them?

Default Arguments in Python Functions: Usage and Examples

Default arguments in a function are parameters with a predefined value set by the function definition. When calling a function, if no argument is provided for a parameter with a default value, the default value will be used. In this way, the function is more flexible and does not require each argument to be specified.

You can define default arguments in the function's parameter list with an assigned value. A function's default arguments are defined as follows:

def function_name(parameter1=default_value1, parameter2=default_value2, ...): 
   # Function body 
   # The code that uses the parameters 
   # A parameter's default value will be used if no value is provided

Example of a function with default arguments:

Code:

def message(name, greeting="Hello"):
    return f"{greeting}, {name}!"
# Calling the function without specifying the 'greeting' argument
result1 = message("Wallace")
print(result1)  # Output: Hello, Wallace!
# Calling the function with a custom 'greeting' argument
result2 = message("Mojca", greeting="Hi")
print(result2)  # Output: Hi, Mojca!

Output:

Hello, Wallace!
Hi, Mojca!

In this example, we defined a function called "message" that takes two parameters: 'name' and 'greeting'. The 'greeting' parameter has a default value of "Hello". When we call the function without providing a value for the 'greeting' parameter, it uses the default value of "Hello". When calling the function, we can also pass a custom 'greeting' value, which will override the default.



Follow us on Facebook and Twitter for latest update.