Skip to main content
\( \newcommand{\lt}{ < } \newcommand{\gt}{ > } \newcommand{\amp}{ & } \)

Section1.1Sage and Declaring Variables

Sage is a programming or scripting language with mathematical capabilities. In order to use it effectively, you need to be familiar with some basic principles.

First, when Sage does a calculation, if we do not capture it somehow, then we will never learn the result. For this purpose, we can capture or store values and results and label those results with a name. We call such a stored result a script variable and the label the variable name. This is always performed by an assignment of the form name = calculation, where the calculation is however we need to generate our result.

Second, in order to learn the value that is stored in the script variable, we need the script to display the result. The simplest way to do this is with a print or pretty_print command.

Third, it is helpful to include comments in scripting code so that we can explain what is going on. This process of adding comments is called documentation and is an important step in programming. In Sage, we use the # character to start a comment and everything on the line after that character is ignored by the computer.

Note1.1.1

The order is important. You would get an error if you entered 3+4=value. The computer would interpret value as the rule for computing something and would try to store it with a label 3+4, but that is not a valid name.

If you use the same name for a label, only the last captured result is remembered. Anything earlier will have been lost. Consider the following script. What do you think it will print? Then try it out.

So far, we have just dealt with numbers. Sage can also deal with algebra. To do this, we need to introduce mathematical variables. These are symbols that represent variables like we think of them in mathematics, and not labels for captured results.

Be careful not to mix the two ideas, because Sage allows you to use an existing label and you might lose a mathematical variable if you use the same label to capture a result.