Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Introduction to Python
using sage
Sage + Python = Awesomeness
This is an introduction to the basic functionality of Python and Sage, with an emphasis on seeing how to handle a worksheet and how to get more detailed help. We will point out a little bit of the power that Sage has hiding in it, but this is not a full-fledged tutorial.
Zero:
The start of it all
There are two (main) ways to use sage: terminal and browser.
Terminal: You can use sagemath from your computer itself. Everything lives on your computer. Uses your computers components, so it'll be faster.
    On Ubuntu, you can type sage
from your computer and it'll open up the terminal. You can then type whatever code you want and hit enter
and you'll get the results.
Browser: You can use sagemath from any website. Everything lives on the cloud (good for collaboration/sharing). Uses cocalc servers, so it'll be slower.
    This file is the browser version. We normally call these "worksheets" and each little box in a worksheet is a "cell". This is where you write you code on the browser. Once you've written your code, you type shift + enter
and you'll get your results.
Let's test out that sage works. Try doing 2+7
in sage.
First things first:
Tabbing & Questions
If you don't know what a function does, type the function, add a ? and hit shift+enter
for a quick description.
Try typing:
fibonacci?
and pressing shift+enter
Congrats! For the next parts, go ahead and read the information and hit shift+enter
each time you want to test something out.
Try doing shift+enter
on the following to test it out. (The first lines makes everything look pretty by using latex =D)
Second:
Data Types
Luckily there are a finite number of data types in Python. This list includes- Booleans
- Integers
- Floats
- Strings
- Sets
- Lists
- Tuples
- Dictionaries
Python is a dynamic language, so there is no need to declare what variable type you are using. You can also change the type of your variables. To know what type a variable is you can just ask for it's type using the type
function. Or you can ask directly if the object is of a certain type using isinstance
.
Full details can be found in the python docs.
Let's first set-up a string and an integer. Notice how their types are different.
Booleans
bool
has one of two values: True
and False
.
There are three boolean operators: and
, or
, & not
.
You can convert something into a boolean by the bool
function.
Notice in the following that True
returns 'bool'
as its type.
Notice that when converting something to boolean, we normally get True, except for when we input .
In particular, the following give us False:
The integer 0
The string ''
We can also do operations on booleans using and
, or
, not
, etc.
Integers/Floats
int
is the python built-in integer type. The problem with the python version is the integer conversion problem.
Due to this restriction, Sage uses its own type called Integer
.
float
is the python built-in rational number type. Due to similar restrictions, Sage uses the RealLiteral
type.
Look at what happens if we force numbers to use python's integers.
This is definitely not true!!!
In order to get around this, sage uses its own definition of integer using the integer ring.
Strings
The str
type is fairly common. You can use single or double quotes. Additionally you can use triple quotes if you want a multi-line string. You can also fill a string using dictionary substitutions as can be seen in the following example.
Concatenation
You can concatenate strings either using ,
or +
. The difference is that ,
will auto-type convert and will add spaces automatically. +
on the other hand assumes everything is a str
variable and will not add spaces.
Sets, lists, tuples, and dictionaries
Because, why not.
There are four more (complicated) types:
set
- is a set of items with no multiplicites or order.list
- is an ordered list of itemstuple
- is the same as a list, but it is immutable (it cannot be changed).dict
- Is an associative array which associates values with keys.
Some basic commands
Constructing stuff
This is how you can construct a set
, list
, tuple
and dict
.
To have only one element in your object, it's generally normal:
Note that for tuples, you can't just have 1 element! Look at what happens if we try and define a tuple with just one element.
If you reaaaaalllly want a tuple with one element, you need to add a comma after the first element to force it to be a tuple.
How many stuff does it have?
Use thelen
function.Is this object present?
Use the in
operator.
Did you notice how for dictionaries
the in operator is looking at the key and not the value? Remember this forever!
How do I access elements?
Use square brackets to access individual items. For dictionaries you use the key. For lists and tuples the counting begins at . Sets have no order so you can't "access" things.Can I modify things?
Only lists and dictionaries! Tuples are immutable, so they can't be altered.How do I add new things?
There are many ways my young padawan.
Sets - Use the add
function
Lists - You can append
a list at the end, extend
a list with another list, or just plain add two lists together.
Tuples - They are immutable, so we can't alter them! We can add two of them together and create a new tuple though.
Dictionaries - Just add a new key and put in a value.
set
example for adding new things
list
example for adding new things
tuple
example for adding new things
Recall that since they are immutable, you can't add directly to a tuple
dict
example for adding new things
Note: For lists we can't add additional items like we do in dictionaries.
Note: We also can't add mutable items as keys for dictionaries.
Russell's paradox
Sets of sets can't happen
If you want a set of a set you need to create a frozenset
. Frozen sets are immutable and therefore they can be placed in a set.
Exercise: Look at the following code and make a guess as to what will be displayed.
But I added too much! How do I delete things I don't want?
For sets we can just discard the item we want. Note that we must discard
the actual element and not the 'index' as indices don't exist in a set.
For a list
we can either delete by index using del
, we can pop
an item out, or we can remove
an item by its value.
For del
you must specify the list with the index you are trying to remove. For pop
you specify the index as well, but unlike del
, it will actually return the item removed so you can use it later if you want. For remove
you specify the value of the thing you want to remove. This is useful if you don't know the index.
Note: remove
will only remove the first time it sees an object. It won't remove all of them.
You can also use splicing. Splicing won't be covered in full here, but if you're interested, here's a good article on it.
For dict
we can do similar things as list. We can del
or we can pop
. Recall that we are using the keys and not the values.
Some other useful commands (Lists only!):
sort
reverse
Some basic commands
Here's a summary of everything we just talked about.Operation | set |
list |
tuple |
dict |
---|---|---|---|---|
Construction | set([]) |
[] |
() |
{} |
One element construction | set([1]) |
[1] |
(1,) |
{1:1} |
Size | len(set) |
len(list) |
len(tuple) |
len(dict) |
Contains | x in set |
x in list |
x in tuple |
key in dict |
Accessing entries | - | list[0] |
tuple[0] |
dict[key] |
Adding stuff | set.add(x) |
list.append(x) list.extend(list2) list3 = list1 + list2 |
tuple3 = tuple1 + tuple2 |
dict[key] = x key must be immutable |
Deleting stuff | set.discard(item) |
list.pop(i) del list[i] list = list[start:end] list.remove(value) |
tuple = tuple[start:end] |
dict.pop(key) del dict[key] |
Exercise:
- Create the list
[5,1,3,6,7,2,12]
. - Remove the element 12.
- Add the element 4.
- Sort the list and reverse it.
The modification problem.
Or things that should be illegal.
Changing lists and dictionaries can have unintended consequences. To see this, let's start off with constructing a list.Note that for theatrical purposes, I'll have you do the heavy work of hitting shift+enter
for each code. Try and think about what you would expect to happen each time before running the code.
This seems fairly normal. We have a list composed with two lists. But now watch what happens when we add an element to our list L
.
WHAT?! That's mental right? So what happens if we change L
to something altogether?
But L2
didn't change!
So what happened? Basically variables in Python work a little differently than we might otherwise think. When creating a variable Python assigns the variable to a slot in your RAM with the data inside of it. When you then use that variable to construct other variables (such as for L2 = [L,L]
) Python doesn't duplicate the data. Instead, it says "create an array with two elements where the information for these elements contained in the slot where L
is". So in essence this new memory slot points to the original slot! Therefore when we alter L
by appending a d
to it, L2
still is pointing to that memory slot and therefore will show the d
now as well.
But what happened when we reconstructed L
?! That is because whenever we do a =
it resets the memory slot. So now L
is pointing to a different slot in RAM and altering it won't affect L2
anymore.
BUT that doesn't mean we can't get weird things happening still! L[0]
is nothing more than just a pointer to the original memory slot that used to contain L
. So what do yu think will happen when we alter this?
Stop this nonsense! How do we fix this?
deepcopy
to the rescue!
Basically, what `deepcopy` does is makes a copy of the data instead of just pointing!
Like this we won't get a lot of this alteration problems.
The None
type
If you want to set a variable but don't want to set it as any particular type, you can use None
Ranges
Lists made easy
Ranges allow us to make numerical lists easily. We use the range
function to construct a range.
If we want all the numbers between 1 and 10 we would do the following:
Note that 10
is not included! This is because range
is "starting" from 1
and going up to (but not including) 10
. Something to note!.
Also, you can skip over every other element if we want.
Or we can go backwards!
Exercise: Use range
to construct the list of even numbers between and (including ).
Bonus: Put it in reverse order.
Third parts the charm:
Control Flows
if
- Does something if the condition is true.for
- Loops through a range of objects.while
- Keeps looping until condition is false.
For more details you can visit the control flow page on the Python docs.
Quick aside: Comparisons
or
 Âand
 Ânot
- Boolean operators==
- Equal!=
- Not equal<
 Â>
 Â<=
 Â>=
- Inequalitiesis
- Object identityis not
- Negated object identity
if
with its siblings elif
and else
.
An if
statement is exactly like what it sounds like. If something is true, then do something.
If we have multiple things we can use elif
and else
to help. elif
stands for "else if". The rest should be easy to understand.
for
for
is used for constructing loops. It does "something" for each item in something.
Exercise: Use a for
loop to print out all the non-even primes from to .
while
while
is a loop that keeps going while a certain condition is true.
Note: be careful of creating infinite loops! Always make sure that your loop WILL end at some point.
Let's look at this through the Collatz conjecture.
for
and list
The super team
We can use for loops in order to create super awesome lists.We can even combine if statements!
And take sums!
Exercise: Find the sume of the non-even primes from to .
Wait, it gets better.... Nesting!
We can nest these lists in order to construct lists of tuples, dictionaries, matrices, etc.These special lists also allow us to grab the keys/values of dictionaries!
Integers vs ints
Revisited
So do you recall how integers in Python have a division problem? Check out this matrix....
That looks wrong... Basically, range will return Python integers and NOT sage integers! This is obviously a problem if we actually want to work with these numbers. So, sage includes with it srange
which is a copy of range
but instead returns sage integers and not Python integers. Let's see this in action.
Part :
Functions
Functions are defined using thedef
statement. We can return things from functions using the return
keyword.Recursion - Catalan Numbers
Complicated recursion - Catalan Numbers part 2
Exercise: Create a function for the fibonacci series and display the first .
Functions can also have default values.
Functions can also return multiple values if desired.
Digraphs!
Sage allows us to construct digraphs using dictionaries. Let's take a sidestep and look at how to construct digraphs and some operations we can do on them.
Exercise: Plot your favourite digraph.
Thanks for reading this tutorial!!!
If you have any suggestions, just email me and let me know =D I'm more than happy to make this more accessible to everyone =) Also, feel free to use this for anything =) The more humans using sage the better =D
Email: [email protected] Website: dermenjian.com