We have seen a few examples already of some common uses of
for loops. In Python, a for loop has an indented structure,
such as
>>> for i in range(5):
print(i)
0
1
2
3
4
print(i). This indentation is important.
In Sage, the indentation is automatically put in for you
when you hit enter after a ``:'', as illustrated below.
sage: for i in range(5):
print(i) # now hit enter twice
0
1
2
3
4
sage:
The symbol = is used for assignment.
The symbol == is used to check for equality:
sage: for i in range(15):
if gcd(i,15) == 1:
print(i)
1
2
4
7
8
11
13
14
if, for, and while statements:
sage: def legendre(a,p):
is_sqr_modp=-1
for i in range(p):
if a % p == i^2 % p:
is_sqr_modp=1
return is_sqr_modp
sage: legendre(2,7)
1
sage: legendre(3,7)
-1
kronecker, which comes with
Sage, computes the Legendre symbol efficiently
via a C-library call to PARI.
Finally, we note that comparisons,
such as ==, !=,
<=, >=, >, <,
between numbers will automatically convert both
numbers into the same type if possible:
sage: 2 < 3.1; 3.1 <= 1 True False sage: 2/3 < 3/2; 3/2 < 3/1 True True
sage: 2 < CC(3.1,1) True sage: 5 < VectorSpace(QQ,3) # output can be somewhat random True
sage: 3.1+2*I<4+3*I 2*I + 3.10000000000000 < 3*I + 4 sage: bool(3.1+2*I<4+3*I) False
is. For example:
sage: 1 is 2/2 False sage: 1 is 1 False sage: 1 == 2/2 True
False because
there is no canonical morphism
True.
Note also that the order doesn't matter.
sage: GF(5)(1) == QQ(1); QQ(1) == GF(5)(1) False False sage: GF(5)(1) == ZZ(1); ZZ(1) == GF(5)(1) True True sage: ZZ(1) == QQ(1) True
WARNING: Comparison in Sage is more restrictive than in
Magma, which declares the
equal to
.
sage: magma('GF(5)!1 eq Rationals()!1') # optional magma required
true
See About this document... for information on suggesting changes.