To define a new function in Sage, use the def
command and a
colon after the list of variable names. For example:
sage: def is_even(n): ... return n%2 == 0 sage: is_even(2) True sage: is_even(3) False
...
above; they are
just to emphasize that the code is indented.
You do not specify the types of any of the input
arguments. You can specify multiple inputs, each of which
may have an optional default value. For example, the function below
defaults to divisor=2
if divisor
is not specified.
sage: def is_divisible_by(number, divisor=2): ... return number%divisor == 0 sage: is_divisible_by(6,2) True sage: is_divisible_by(6) True sage: is_divisible_by(6, 5) False
You can also explicitly specify one or either of the inputs when calling the function; if you specify the inputs explicitly, you can give them in any order:
sage: is_divisible_by(6, divisor=5) False sage: is_divisible_by(divisor=2, number=6) True
In Python, blocks of code are not indicated by
curly braces or begin and end blocks as in many
other languages. Instead, blocks of code are indicated
by indentation, which must match up exactly.
For example, the following is a syntax error because
the return
statement is not indented the same amount
as the other lines above it.
sage: def even(n): ... v = [] ... for i in range(3,n): ... if i % 2 == 0: ... v.append(i) ... return v Syntax Error: return v
sage: def even(n): ... v = [] ... for i in range(3,n): ... if i % 2 == 0: ... v.append(i) ... return v sage: even(10) [4, 6, 8]
Semicolons are not needed at the ends of lines; a line is in most cases ended by a newline. However, you can put multiple statements on one line, separated by semicolons:
sage: a = 5; b = a + 3; c = b^2; c 64
If you would like a single line of code to span multiple lines, use a terminating backslash:
sage: 2 + \ ... 3 5
In Sage, you count by iterating over a range
of integers. For example, the first line below
is exactly like for(i=0; i<3; i++)
in C++ or Java:
sage: for i in range(3): ... print i 0 1 2
for(i=2;i<5;i++)
.
sage: for i in range(2,5): ... print i 2 3 4
for(i=1;i<6;i+=2)
.
sage: for i in range(1,6,2): ... print i 1 3 5
Often you will want to create a nice table to display numbers you have computed using Sage. One easy way to do this is to use string formatting. Below, we create three columns each of width exactly 6 and make a table of squares and cubes.
sage: for i in range(5): ... print '%6s %6s %6s'%(i, i^2, i^3) 0 0 0 1 1 1 2 4 8 3 9 27 4 16 64
The most basic data structure in Sage is the list,
which is -- as the name suggests -- just a list of arbitrary objects.
For example, the range
command that we used creates a list:
sage: range(2,10) [2, 3, 4, 5, 6, 7, 8, 9]
Here is a more complicated list:
sage: v = [1, "hello", 2/3, sin(x^3)] sage: v [1, 'hello', 2/3, sin(x^3)]
List indexing is 0-based, as in many programming languages.
sage: v[0] 1 sage: v[3] sin(x^3)
Use len(v)
to get the length of v
, use
v.append(obj)
to append a new object to the end of v
,
and use del v[i]
to delete the ith entry of v
:
sage: len(v) 4 sage: v.append(1.5) sage: v [1, 'hello', 2/3, sin(x^3), 1.50000000000000] sage: del v[1] sage: v [1, 2/3, sin(x^3), 1.50000000000000]
Another important data structure is the dictionary (or associative array). This works like a list, except that it can be indexed with almost any object (the indices must be immutable):
sage: d = {'hi':-2, 3/8:pi, e:pi} sage: d['hi'] -2 sage: d[e] pi
You can also define new data types using classes. Encapsulating
mathematical objects with classes is a powerful technique that can
help to simplify and organize your Sage programs.
Below, we define a class that represents the
list of even positive integers up
to n; it derives from the builtin type list
.
sage: class Evens(list): ... def __init__(self, n): ... self.n = n ... list.__init__(self, range(2, n+1, 2)) ... def __repr__(self): ... return "Even positive numbers up to n."
__init__
method is called to initialize the object
when it is created; the __repr__
method prints the object
out. We call the list constructor method in the second line
of the __init__
method.
We create an object of class Evens
as follows:
sage: e = Evens(10) sage: e Even positive numbers up to n.
Note that e
prints using the __repr__
method
that we defined. To see the underlying list of numbers,
use the list
function:
sage: list(e) [2, 4, 6, 8, 10]
We can also access the n
attribute or treat e
like
a list.
sage: e.n 10 sage: e[2] 6
See About this document... for information on suggesting changes.