Arguments in a function must be given in the right order so Python knows which value goes to which parameter.
0
0
Argument order rules in Python
Introduction
When you write a function that takes multiple inputs.
When you call a function and want to give values to its parameters.
When you want to avoid mistakes by mixing up inputs.
When you use both positional and keyword arguments in a function call.
When you want to use default values but still provide some arguments.
Syntax
Python
def function_name(positional1, positional2, /, positional_or_keyword1, positional_or_keyword2, *, keyword_only1, keyword_only2): pass
Positional-only arguments come first and must be given by position.
Keyword-only arguments come after * and must be given by name.
Examples
name is positional-only, greeting can be positional or keyword, punctuation is keyword-only.Python
def greet(name, /, greeting='Hello', *, punctuation='!'): print(f"{greeting}, {name}{punctuation}")
Shows different ways to call the function following argument order rules.
Python
greet('Alice') greet('Bob', 'Hi') greet('Carol', greeting='Hey', punctuation='.')
Sample Program
This program shows how to use positional-only, positional-or-keyword, and keyword-only arguments in a function.
Python
def describe_pet(name, /, species='dog', *, age=None): description = f"Pet name: {name}, species: {species}" if age is not None: description += f", age: {age} years" print(description) describe_pet('Buddy') describe_pet('Mittens', 'cat') describe_pet('Goldie', age=2)
OutputSuccess
Important Notes
Positional-only arguments are marked with a slash / in the function definition.
Keyword-only arguments come after an asterisk * and must be named when calling the function.
Using argument order rules helps avoid confusion and bugs in your code.
Summary
Arguments have a specific order: positional-only, positional-or-keyword, then keyword-only.
Positional-only arguments must be given by position, keyword-only must be named.
Following these rules makes your functions easier to use and understand.