Section 1.1 Intro to Sage
You can execute and modify Sage code directly within the SageMathCells embedded on this webpage. Cells on the same page share a common memory space. To ensure accurate results, run the cells in the sequence in which they appear. Running them out of order may cause unexpected outcomes due to dependencies between the cells.
Subsection 1.1.1 Sage as a Calculator
Before we get started with discrete math, let’s see how we can use Sage as a calculator. Here are the basic arithmetic operators:
- Addition:
+
- Subtraction:
-
- Multiplication:
*
- Exponentiation:
**
, or^
- Division:
/
- Integer division:
//
- Modulo:
%
There are two ways to run the code within the cells:
- Click the Evaluate (Sage) button located under the cell.
- Use the keyboard shortcut Shift + Enter if your cursor is active in the cell.
Subsection 1.1.2 Variables and Names
We can assign the value of an expression to a variable. A variable is a name that refers to a value in the computer’s memory. Use the assignment operator
=
to assign a value to a variable. The variable name is on the left side of the assignment operator, and the value is on the right side. Unlike the expressions above, the assignment statement does not display anything. To view the value of a variable, type the variable name and run the cell.When choosing variable names, use valid identifiers.
- Identifiers cannot start with a digit.
- Identifiers are case-sensitive.
- Identifiers can include:
- letters (
a
-z
,A
-Z
) - digits (
0
-9
) - underscore character
_
- Do not use spaces, hyphens, punctuation, or special characters when naming identifiers.
- Do not use keywords as identifiers.
Below are some reserved keywords that you cannot use as variable names:
False
, None
, True
, and
, as
, assert
, async
, await
, break
, class
, continue
, def
, del
, elif
, else
, except
, finally
, for
, from
, global
, if
, import
, in
, is
, lambda
, nonlocal
, not
, or
, pass
, raise
, return
, try
, while
, with
, yield
.Use the Python
keyword
module to check if a name is a keyword.The output is
True
because if
is a keyword. Try checking other names.