Python for C++ Programmers
Chapter 7: Functions
Positional and default arguments
Like in C++, the basic way of calling a function is via positional arguments. That is, assign arguments to parameters by matching their position.
Python allows you to also provide default arguments, so that a poor user does not have to explicitly provide a value for every single parameter.
def do_something(a, b, c=2, d="great", e=5, f="john", g="python", h=-1, i=0, j=[]):
print(f"{a}; {b}; {c}; {d}; {e}; {f}; {g}; {h}; {i}; {j}")
return None
Users trying to call the function above must provide the first two positional arguments. Then they can optionally provide any additional arguments that they need. Anything else that is not given will use the default arguments that the function defined.
>>> x = do_something("first", "second")
first; second; 2; great; 5; john; python; -1; 0; []
>>> x = do_something("first", "second", "arg for c", "arg for d")
first; second; arg for c; arg for d; 5; john; python; -1; 0; []
The following function definition is not allowed. Why?
def my_function(a="first", b, c, d="default d"):
print(f"{a}; {b}; {c}; {d}")
Try it out! It will result in a syntax error. The error message should tell you exactly why.