Sobes.tech
Junior — Middle

Is it possible to set a default value for a positional argument in a function or method?

sobes.tech AI

Answer from AI

In Python, you cannot set a default value for positional arguments in the sense that positional arguments without a name are always required. However, you can set default values for named (keyword) arguments, which can be passed either positionally or by name.

If you want an argument to be optional and have a default value, you should declare it after the required positional arguments:

def func(a, b=10):
    print(a, b)

func(5)      # Outputs: 5 10
func(5, 20)  # Outputs: 5 20

In Python 3.8+, you can use the syntax of positional-only arguments with / and named arguments with *, but by default, default values are set for arguments that can be passed by name.

Therefore, if you want an argument with a default value, make it either a named argument or a positional-or-named argument, but not purely positional without a default value.