We saw in the previous section that python can do fairly complicated computations for you so it seems to provide a good calculator for our purposes. How about performing repetitive tasks?
Suppose that you want to check if the point
is on the curve
>>> def on_curve(x,y): ... """See if (x,y) is on the curve y**2==x**3+x+1725858433486651246286""" ... return y**2==x**3+x+1725858433486651246286We have just defined a function. There are several things to notice here. First line: def on_curve(x,y): all function definitions start with def, then follows the name of the function (on_curve, in this case) and then the parameters of the function, x and y. Finally, the ``:''. If you forget the colon you will see all sorts of strange complaints from python.
The second line is informative, a way of saying what the function does. It is (very) convenient to use it, especially when you write several functions with clever names such as f. Notice that the message goes with triple quotes.
The third line is where things happen: the return value of the
function is the comparison of the equation. So on_curve(x,y) will be
0 if
is not on the curve and
otherwise.
We have skipped one essential detail: look at the indentation of the function. It is nice because it makes the function easy to read. Furthermore, if you don't indent your code as we did, python will complain.
Now that we have defined our function we can use it:
>>> on_curve(1342,41543452354) 1 >>> on_curve(-1342,41543452354) 0and we see that while
Usually, functions are more involved than our on_curve example. In almost all cases it is more convenient to write (and perfect) your functions using a text editor and then load them into python. Our next section describes how to do that, so that then we can tackle our first real application: computing the sum of points on an elliptic curve.