Computer Science

Explain with a code example the usage of default arguments and keyword arguments.

Python Functions

2 Likes

Answer

Default arguments — Default arguments are used to provide a default value to a function parameter if no argument is provided during the function call.

For example :

def greet(name, message="Hello"):
    print(message, name)

greet("Alice")          
greet("Bob", "Hi there")
Output
Hello Alice
Hi there Bob

In this example, the message parameter has a default value of "Hello". If no message argument is provided during the function call, the default value is used.

Keyword arguments — Keyword arguments allow us to specify arguments by their parameter names during a function call, irrespective of their position.

def person(name, age, city):
    print(name, "is", age, "years old and lives in", city)

person(age=25, name="Alice", city="New York")
person(city="London", name="Bob", age=30)
Output
Alice is 25 years old and lives in New York
Bob is 30 years old and lives in London

In this example, the arguments are provided in a different order compared to the function definition. Keyword arguments specify which parameter each argument corresponds to, making the code more readable and self-explanatory.

Both default arguments and keyword arguments provide flexibility and improve the readability of code, especially in functions with multiple parameters or when calling functions with optional arguments.

Answered By

1 Like


Related Questions