You can initialize the parameters of a function by setting a default value.
def f(a=1): print(a) f(5) # 5 f() # 1 f(1) # 1
def f(a,b): print (a+b*2) f(1,2) # prints 5 f(a=1,b=2) # prints 5 f(b=1,a=2) # prints 4 f(a=1,2) # ERROR
We’ll get an error at the last call because there is the rule that named arguments must be written after the normal parameters. What you should keep in mind is that you should not mess with the arguments order. It is better to know their order, or to specify all of them.
This is also true with the default parameters. You cannot initialize a parameter and not the parameters following it. Just think about that. Thus, defining the following function will give us an error:
def f(a,b=2,c): print (a+b*2+c*3) # SyntaxError: non-default argument follows default argument
To solve it, we either remove the default value for
b or we set a default
def f(a,b,c): print (a+b*2+c*3) # this is a correct definition def g(a,b=2,c=50): print (a+b*2+c*3) # this is a correct definition
To define more arguments you can define a list as a parameter:
def f(*args): print(args) f(1) # prints 1 f(2,3) # prints 2 f() # we'll get an error
To fix that error we can write:
def f(*args): if len(args)>0: print(args) f() # we'll get nothing
As a better alternative, you can send a list of parameters as a dictionary. These are called keyword arguments.
def f(**kwargs): if kwargs['term']: print('"term" was defined as: '+ kwargs['term']) else: print('"term" was not defined') f(term="baseball") # prints: "term" was defined as: baseball f(something="baseball") # ERROR
The last line gives us an error. We should have checked if the
argument was sent. This is a common mistake when using keyword arguments.
Many times this kind of mistakes are hard to debug. The lazy programmer
presumes that if the keyword argument was not set, trying to access its value
False, which as you can see is not true. We must remember to
def f(**kwargs): if 'term' in kwargs.keys(): print('"term" was defined as: '+ kwargs['term']) else: print('"term" was not defined')
Of course, you can set as many keyword arguments as you like.
Don’t overuse the array arguments (
*args) and the keyword arguments
**kwargs) because your code might become difficult-to-understand by
other programmers. This will not bring you benefits in a company, because
your coworkers will have a hard time reading your work.