Default Argument values and keyword arguments

In Python, functions can have default argument values and keyword arguments.

Default argument values are values that are assigned to function parameters when they are declared. If a value is not passed for that parameter when the function is called, the default value will be used instead. Here’s an example:

pythonCopy codedef greet(name, greeting="Hello"):
    print(greeting, name)

greet("Alice")   # Output: Hello Alice
greet("Bob", "Hi")  # Output: Hi Bob

In the above example, the greeting parameter has a default value of “Hello”. When greet is called with just the name argument, the default value is used. When greet is called with both name and greeting, the greeting argument overrides the default value.

Keyword arguments are arguments passed to a function with a specific name or keyword. They are useful when you want to specify values for specific parameters without worrying about the order in which they are passed. Here’s an example:

pythonCopy codedef power(base, exponent):
    return base ** exponent

result1 = power(2, 3)    # Output: 8
result2 = power(exponent=3, base=2)  # Output: 8

In the above example, we define a function power that takes two arguments, base and exponent. In the first call to power, we pass the arguments in the order they are defined in the function signature. In the second call, we pass the arguments using the keyword exponent and base, which allows us to pass them in any order.

Note that default argument values and keyword arguments are optional features in Python, and not every function needs to use them. However, they can make your code more readable and easier to use.

Apply for Python Certification!

https://www.vskills.in/certification/certified-python-developer

Back to Tutorials

Get industry recognized certification – Contact us

Menu