How to Create a Python Function with Optional Parameters?

Estimated read time 2 min read

To create a Python function with optional parameters, you can define the function with default values for some or all of its parameters. Here’s an example:

def greet(name, greeting="Hello"):
    print(greeting + ", " + name + "!")

In this example, we define a function called greet that takes two parameters: name and greeting. The greeting parameter has a default value of "Hello".

The function body consists of a single statement that uses the print function to display a personalized greeting message to the console, based on the values of the name and greeting parameters.

To call the function, you can pass a value for the name parameter and optionally a value for the greeting parameter, like this:

greet("Alice")           # Output: "Hello, Alice!"
greet("Bob", "Goodbye")  # Output: "Goodbye, Bob!"

In the first example, we call the greet function with only the name parameter. Since we don’t pass a value for greeting, the function uses the default value of "Hello".

In the second example, we call the greet function with both the name and greeting parameters. The function uses the values of "Bob" and "Goodbye", respectively, to generate the message “Goodbye, Bob!”.

Note that you can use any valid Python data type as a parameter with default values, including strings, numbers, lists, and objects. You can also define functions with multiple parameters, some of which have default values and some of which do not.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply