How do you define an optional parameter with a default value in Python?

Experience Level: Junior
Tags: Python

Answer

To define an optional parameter with a default value, add the default value prefixed with an equal sign after the parameter name and type in the method signature.

Example:

def do_something(name: str="Anonymous"):
    print("Name: " + name)

Python for beginners
Python for beginners

Are you learning Python ? Try our test we designed to help you progress faster.

Test yourself