cheese cheese |
|
3 3 |
(5, cheese) (5, cheese) |
|
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] |
10 10 |
[10, 11, 12, 13, 14, 15] [10, 11, 12, 13, 14, 15] |
Suppose we want just the last element of L: we can access that by L[len(L)-1], which is a pain to type. Fortunately there is shorthand for this
19 19 19 19 |
[15, 16, 17, 18] [15, 16, 17, 18, 19] [15, 16, 17, 18] [15, 16, 17, 18, 19] |
If we wish to square each element of the list, starting with the fifth from the end, going to the end, and add them all up, we could do the following
1455 1455 |
What is the meaning of the
total+=$i^2$
line? It is shorthand for
total = total + $i^2$
Mutiple for loops can be nested, with multiple indentation
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] |
|
|
|
While loops are easy to get wrong and end up with an infinite loop
Traceback (click to the left of this block for traceback) ... __SAGE__ ^CTraceback (most recent call last): File "<stdin>", line 1, in <module> File "_sage_input_30.py", line 10, in <module> exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("aT0xCnRvdGFsPTAKd2hpbGUgaSAgPCAxMDoKICAgIHRvdGFsKz1p"),globals())+"\\n"); execfile(os.path.abspath("___code___.py")) File "", line 1, in <module> File "/tmp/tmpY0soex/___code___.py", line 5, in <module> exec compile(u'while i < _sage_const_10 :\n total+=i File "", line 2, in <module> File "sage/ext/interrupt/interrupt.pyx", line 203, in sage.ext.interrupt.interrupt.sage_python_check_interrupt (/usr/local/sage-6.10/src/build/cythonized/sage/ext/interrupt/interrupt.c:1891) File "sage/ext/interrupt/interrupt.pyx", line 88, in sage.ext.interrupt.interrupt.sig_raise_exception (/usr/local/sage-6.10/src/build/cythonized/sage/ext/interrupt/interrupt.c:925) KeyboardInterrupt __SAGE__ |
73855412 73855412 |
|
45 45 |
Example of a function. Suppose we wish to compute x+sin(x) for llots of values of x.
|
sin(1) + 1 sin(1) + 1 |
sin(2) + 2 sin(2) + 2 |
2.90929742682568 2.90929742682568 |
Bad code follows!
|
sin(1) + 1 sin(1) + 1 |
sin(1) + 1 sin(1) + 1 |
False False |
|