Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Avatar for Blaec (CSO) Tasks and Strategy Outline.
Download

Tutorial Release 10.4 The Sage Development Team https://doc.sagemath.org/pdf/en/tutorial/sage_tutorial.pdf

Sage is free, open-source math software that supports research and teaching in algebra, geometry, number theory, cryptography, numerical computation, and related areas. Both the Sage development model and the technology in Sage itself are distinguished by an extremely strong emphasis on openness, community, cooperation, and collaboration: we are building the car, not reinventing the wheel. The overall goal of Sage is to create a viable, free, open-source alternative to Maple, Mathematica, Magma, and MATLAB.

This tutorial is the best way to become familiar with Sage in only a few hours. You can read it in HTML or PDF versions, or from the Sage notebook (click Help, then click Tutorial to interactively work through the tutorial from within Sage).

This work is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

https://creativecommons.org/licenses/by-sa/3.0/

386 views
ubuntu2204
Kernel: SageMath 10.4

Generating a Table with String Formatting

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.

from sage.all import * 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

Creating a List in Sage

The most basic data structure in Sage is the list, which is – as the name suggests – just a list of arbitrary objects. For example, using range, the following command creates a list:

from sage.all import * list(range(Integer(2), Integer(10)))
[2, 3, 4, 5, 6, 7, 8, 9]

Here is a more complicated list:

from sage.all import * v = [Integer(1), "hello", Integer(2)/Integer(3), sin(x**Integer(3))] v
[1, 'hello', 2/3, sin(x^3)]

List Indexing

List indexing is 0-based, as in many programming languages. Accessing elements of the list:

v[Integer(0)]
1
v[Integer(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 ii-th entry of v.

len(v)
4
v.append(RealNumber(1.5)) v
[1, 'hello', 2/3, sin(x^3), 1.50000000000000]
del v[Integer(1)] v
[1, 2/3, sin(x^3), 1.50000000000000]

Creating a Dictionary in Sage

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).

from sage.all import * d = {"hi": -Integer(2), Integer(3)/Integer(8): pi, e: pi} d["hi"]
-2
d[e]
pi