Default values

In some cases, it is convenient to have a default value for a specific argument, so that we won't need to state it explicitly every time. For example, we can assume that most of the time, we need to get a negative square root (depending on the case, of course), and it would be a waste of time to explicitly define p=2 every time. In this case, we'll have to modify our code just a bit, by p=2 within the parentheses. Here is how the code would appear:

def negative_power(v, p=2):
‘''Return negative value v in power p'''
return -1 * (v**p)

We still have to define v every time, but p is now optional – if we don't state it explicitly, it will be assumed to be equal to 2. The following code illustrates the case. Once we don't explicitly state the value of p, the function falls back to p=2; therefore, every value (2 in this case) of v will be squared and returned with a negative sign:

negative_power(2, 3)
>>> -8

negative_power(2)
>>> -4

There is an important rule to follow here. According to Python syntax, arguments with the default values have to be defined after all the others with no default values, otherwise Python will raise a syntax error:

>>> def negative_power(p=2, v): 
'''Return negative value v in power p'''
return -1 * (v**p)

File "<ipython-input-9-9a12e59bef45>", line 1
def negative_power(p=2, v):
^
SyntaxError: non-default argument follows default argument

There is some logic to that – the important parameters should be kept both first and required (to avoid any possibility of forgetting to state them), and the optional ones kept in the end.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.237.172