Search⌘ K
AI Features

Functions with Optional Arguments

Explore how to define Python functions that accept optional arguments using *args for positional and **kwargs for keyword arguments. Understand how these features enhance function flexibility and make your code more adaptable to different input scenarios.

We'll cover the following...

This section brings detailed information about an eminently used feature in Python programming. Getting a firm hold on this concept will make you a competent developer, as it brings wonders.

The *args and **kwargs parameters

The args and kwargs parameters allow a function to accept optional arguments.

  • The keyword args means positional arguments.
  • The keyword kwargs means keyword arguments.

Let’s see a simple example to get a basic understanding of these parameters.

Python 3.10.4
def func(fixed, *args, **kwargs):
print(fixed)
if args: # Optional positional arguments
print(args)
if kwargs: # Optional keyword arguments
print(kwargs)
func('Educative')
func('Eduactive', 1, 2, 3)
func('Eduactive', 1, 2, 3, level='advanced', language='Python3')

In the code above, we define a ...