Skip to main content
Logo image

Discrete Math with SageMath: Learn math with open-source software

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 explore how Sage can be used as a calculator. Here are the basic arithmetic operators:
  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • ** or ^ (Exponentiation)
  • / (Division)
  • // (Integer division)
  • % (Modulo - remainder of division)
There are two ways to run the code within the cells:
  • Click the Evaluate (Sage) button under the cell.
  • Use the keyboard shortcut Shift + Enter while the cursor is active in the cell.
Try the following examples:
Sage supports two exponentiation operators:
Division in Sage:
Integer division and modulo:

Subsection 1.1.2 Variables and Names

Variables store values in the computer’s memory. This includes value of an expression to a variable. Use the assignment operator = to assign a value to a variable. The variable name is on the left side, and the value is on the right. Unlike the expressions above, an assignment does not display anything. To view a variable’s value, type its name and run the cell.
When choosing variable names, follow these rules for valid identifiers:
  • Identifiers cannot start with a digit.
  • Identifiers are case-sensitive.
    • Letters (a-z, A-Z)
    • Digits (0-9)
    • Underscore (_)
  • Do not use spaces, hyphens, punctuation, or special characters while naming your identifiers.
  • Do not use reserved keywords as variable names.
Python has a set of reserved keywords that cannot be used 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.
To check if a word is a reserved keyword, use the keyword module in Python.
The output is True because if is a keyword. Try checking other names.