CBSE Class 12 Computer Science Question 3 of 27

Working with Functions — Question 6

Back to all questions
6
Question

Question 6

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

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.

Get the Bright Tutorials app Stuck on a question? Ask Bright Buddy — your AI tutor — for step-by-step help in the app.