Skip to main content

Subsection 1.3 Programming in Sage

Since SageMath is an extension of the Python programming language, it allows, with few exceptions, the use of standard Python programming constructs. Knowledge of Python is not essential for using Sage. However, users with a Python programming background will have an advantage. Users who are already fluent in Python can safely skip this subection.
Use of if-else statements
if and else can be combined together as elif. Let us look at the following codes.
For Loops
Loops are essentially used for performing same computation several times. We also given example of use of break and continue inside loops.

Example 1.3.2.

Let us print all the twin primes between 1 and 50 using a for loop.

Example 1.3.3.

In this example, we approximate the Euler number \(e:=\sum_{k=0}^\infty\frac{1}{k!}\) as a sequence of partial sums \(e \approx \sum_{k=0}^n\frac{1}{k!}\) using list comprension.

Example 1.3.4.

The \(n\)-th Fibonacci number \(F_n\) is defined by the recurrence relation
\begin{equation*} F_n = f_{n-1}+F_{n-2} \text{ for } n\geq 2, F_0=0, F_1=1. \end{equation*}
We can obtain Fibonacci sequence using matrix multiplication. Let us assume that \(X_0=\begin{pmatrix} F_0 \\ F_1\end{pmatrix}\) and \(A=\begin{pmatrix} 0 \amp 1 \\ 1 \amp 1\end{pmatrix}\text{.}\) The \(X_n=A^nX_0\) gives \(\begin{pmatrix} F_n \\ F_{n+1}\end{pmatrix}\text{.}\) Note that SageMath has inbuilt function fibonacci(n) to find the \(n\)-th Fibonacci number. Although the sequence \(F_n\) diverges, the ratio \(\frac{F_{n+1}}{F_n}\) tends to a real number which is called the Golden Ratio. Let us find the numerical value of the Golden Ratio within the error \(0.0001\text{.}\)
Use of break and continue
In SageMath, the break statement is used to terminate a loop immediately once a condition is met, while the continue statement skips the current iteration and moves on to the next one. These two constructs are useful in controlling the flow of loops and improving efficiency.
In the following program, we demonstrate the use of both break and continue in the process of checking whether a number is prime: