To create a list of integers, starting at 0 and stopping before n, use srange(n).
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
(<type 'sage.rings.integer.Integer'>, <type 'int'>) (<type 'sage.rings.integer.Integer'>, <type 'int'>) |
|
|
The reason for using srange() rather than range() is that the elements of the list produced are of type Integer rather than int.
Given a list $L$, we can step through the elements one by one by using the for command.
(0, 0) (1, 1) (2, 4) (3, 9) (4, 16) (5, 25) (6, 36) (7, 49) (8, 64) (9, 81) (0, 0) (1, 1) (2, 4) (3, 9) (4, 16) (5, 25) (6, 36) (7, 49) (8, 64) (9, 81) |
1 2 3 4 Fred 1 2 3 4 Fred |
|
[[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]] [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]] |
|
We can access the $k$th element of a list $L$ by asking for $L[k]$.
Suppose we wanted a list-like object, but only wanted to call it for primes: for example,
an object psquared, where psquared[p] should give us $p^2$.
|
9 Don't be an idiot 2 3 4 9 9 Don't be an idiot 2 3 4 9 |
False False |
True True |
(2, 4) (2, 4) |
|
{2: 4, 3: 9, 5: 25} {2: 4, 3: 9, 5: 25} |
{2: 4, 3: 10, 5: 25} {2: 4, 3: 9, 5: 25} {2: 4, 3: 10, 5: 25} {2: 4, 3: 9, 5: 25} |
|
{2: 4, 3: 9, 5: 25, 7: 49} {2: 4, 3: 9, 5: 25, 7: 49} |
While loops: allow us to use a conditional statement to determine whether to continue going through the loop
0 -1 2 3 -4 5 -6 7 -8 -9 0 -1 2 3 -4 5 -6 7 -8 -9 |
Another useful thing to do with while loops is use flags
3 5 17 257 65537 3 5 17 257 65537 |
|
|
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'Fred'] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'Fred'] |
|