You can assign default values to arguments of a function. If you do, then the user does not have to supply the value of that parameter, However, the user can still override the value.
def fraction(nom, denom=1): return nom * 1.0 / denom print "fraction(1) =", fraction(1) print "fraction(2) =", fraction(2) print "fraction(1, 2) = ", fraction(1,2)
Values can be assigned to only last arguments in the argument lists. That is, if you assign value to an argument but not the next one, you will end up with a syntax error.
For example, the following is valid:
def do_something(a, b, c=0, d=10): print "hello"
However, the following is invalid:
def do_something(a=10, b, c, d=9): print "hello"
Example Usage: Recall the newton
function that is used to compute approximate square root.
def newton(x, y): if abs(x**2 - y) <= 1e-6: return x else: return newton(0.5 * (x + y*1.0/x), y)
The above function says that the estimate x is good enough if |x^2 - y| \leq 10^{-6}. If we want the user to set the threshold himself, we can add another parameter as follows:
def newton(x, y, tolerance): if abs(x**2 - y) <= tolerance: return x else: return newton(0.5 * (x + y*1.0/x), y, tolerance)
However, this would require the user to supply the tolerance every time he calls the function. This makes the function harder to use.
If we make tolerance an optional argument, the function becomes as easy to use as the first version, while allowing the user to control the tolerance himself.
def newton(x, y, tolerance=1e-6): if abs(x**2 - y) <= tolerance: return x else: return newton(0.5 * (x + y*1.0/x), y, tolerance) print newton(1, 3) print newton(1, 3, 1e-12) print newton(1, 3, 1e-2)