next up previous
Next: Better interface = Emacs Up: Using Python for computing Previous: What?


Functions

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 $ (a,b)$ is on the curve

$\displaystyle y^2 = x^3 + x + 1725858433486651246286.$ (1)

You can do this as we did above, but if you want to do this same operation several times it is useful to define a function that does the computation for you:
>>> 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+1725858433486651246286
We 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 $ (x,y)$ is not on the curve and $ 1$ 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)
0
and we see that while $ (1342,41543452354)$ is on the curve, $ (-1342,41543452354)$ is not.

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.


next up previous
Next: Better interface = Emacs Up: Using Python for computing Previous: What?
Javier Fernandez 2003-06-24