Skip to main content

Appendix B Intro to Sage and Python

Question B.0.1.

What is Python?

Python is a high level language, optimized for reading by people instead of machines. It is an interpreted language. It is usually used in an interactive fashion, rather than compiled directly to machine code (like Java or C). Colons are used occasionally, but not for every line and white space and indentation is important.

Variables are always important. In Python, you do not have to declare a variable before defining it. You could define it to be an integer on one line and a string on the next line.

Another important tool is a for-loop to loop over a range of values.

We will use lots of lists, normally with numbers but you can put any variable type in a list. Lists are mutable, so you can change their length, number of elements, and the element values. These are always formatted with square brackets and are often created with append statements.

List Comprehensions are a shorthand way of creating lists with a for loop.

The last tool you should be able to use is an if statement.

Functions are very useful. You will see lots of them in the code I have written for this textbook, but you will not necessarily need to write your own. Functions start with def followed by your name for the function. Any variables that will be input with the function should be in the top line also. Functions should end with return to specify the output of the function. All the commands inside the function should be indented.

Question B.0.2.

What is Sage?

Sage, or sometimes SageMath, is an open source mathematical software package. It uses Python as its base language, but has many additional mathematical features on top. We already saw the use of ^ for exponentiation. A few other examples are below. You'll see lots more throughout this course.

Question B.0.3.

What are interactive Sage cells?

One of the nice features of Sage is that you can imbed it directly into a webpage and it connects to a remote server to run the calculation. This is the way it is featured in the book. There are both regular Sage cells where you interact directly with the code (as in all the example code above) and interactive Sage cells where you can change the input parameters without directly editing the code. Below is an example of an interactive Sage cell with two different types of interaction outside the code, a slider and an input box.