Python is used as user interface in sagemath.
We can define variables, like variable ‘a’ with integer value ‘2019’. The last expression of some input cell is represented in an output cell.
a = 2019
a
Only the last one; so the first ‘a’ will not be represented.
a
a
You can always enforce a string representation with ‘print()’.
print(a)
a
You also assign two variables simultaneously:
a, b = 2019, 426
String formatting is also provided by python:
print('{} and {}'.format(a, b))
An example algorithm (Euclidean algorithm) with our first control structure: a while loop
a, b = 2019, 426
n, m = a, b
while n != 0:
m, n = n, m % n
print('The gcd of {} and {} is {}'.format(a, b, m))
We can encapsulate this algorithm in a function. ‘def’ introduces a function. ‘n’ and ‘m’ are parameters. ‘return’ specifies the return value.
def our_gcd(n, m):
while n != 0:
m, n = n, m % n
return m
Call the function named ‘our_gcd’
print(our_gcd(a, b))
A partial verification test for ‘our_gcd’:
# a for-loop iterates from 1 (incl.) to 100 (excl.): 1, 2, …, 99
for i in range(1, 100):
# ‘our_gcd’ is the function defined above, ‘gcd’ is provided by sagemath (NOT python!)
if our_gcd(i, 56) != gcd(i, 56):
# raising an exception halts the program and prints an error message
raise ValueError('our_gcd yields invalid result for {} and {}'.format(i, 56))
You can also rename/assign functions and all objects in python can be printed:
glt_gcd = our_gcd
print(glt_gcd)
A simple function with a docstring (i.e. function documentation string). A docstring is given if the first expression is an unassigned string.
def inc(a):
"""Returns the argument incremented by one"""
return a + 1
‘assert’ can be used to test invariants:
assert inc(41) == 42
‘help’ shows the function documentation with the docstring:
help(inc)
With sagemath, an appended question mark also shows the documentation:
gcd?
With sagemath, two appended question marks shows the source code (might be cython source code):
gcd??