How to make an optional parameter in Python functions

Learn how to make optional parameters in Python functions, with an example & explanation.

Optional Parameters in Python

Python functions can have optional parameters that are passed in when the function is called. These are also known as keyword arguments and can be used to provide additional information to the function. In Python, you specify an optional parameter by providing a default value when the parameter is declared in the function definition. This default value is used when the argument is not provided when the function is called.

For example, we can create a simple function that prints out a message. This function takes two parameters, a string message and an optional boolean value. The boolean value is used to determine whether to print the message in all caps. If the boolean is not provided, the message will be printed in lowercase.


def print_msg(message, all_caps=False):
    if all_caps:
        print(message.upper())
    else:
        print(message)

# Print the message in lowercase
print_msg("Hello World")

# Print the message in all caps
print_msg("Hello World", all_caps=True)

In the example above, the second parameter, all_caps, is an optional parameter. The default value for this parameter is False, so if it is not provided when the function is called, the message will be printed in lowercase. If it is provided as True, then the message is printed in all caps.

Optional parameters are a useful feature in Python, as they allow you to provide additional information to a function without having to pass in all the arguments every time. It is important to note, however, that optional parameters must always be the last parameters specified in the function definition, otherwise an error will be raised.

Answers (0)