Andres Mejia Andres Mejia - 1 year ago 52
Python Question

error in "if" loop (Sage)

I'm using "Sage," but I do not think that it is relevant for this question.

I have made the following definitions, and attempted to implement an if loop:

Q = DiagonalQuadraticForm(ZZ,[1,1,1,1])
L = Q.representation_number_list(10)
for i in range(len(L)):
if L[i] == 0 % 2:
print i

Upon looking up Python demos, it seems as though my syntax is correct and (I haven't been made aware of any syntax errors.)

However, nothing is being printed! In fact, if I declare "i" in the next textbox, all that displays is "9," which doesn't change despite my fiddling with the modulus. What is wrong?


Modulus syntax in Python (and most other programming languages) is not the same as mathematical notation. In math, you write

a ≡ b (mod n)

to indicate that a and b are congruent modulo n. In programming languages, modulus is treated as an arithmetic operation on a and n, analogous with division (it returns the remainder of the division rather than the quotient). To determine if the number is congruent with another number, you compare that remainder with the number, so it's written as:

a % n == b

Therefore, your if statement should be:

if L[i] % 2 == 0:

When you write

if L[i] == 0 % 2:

it's parsed as:

if L[i] == (0 % 2):

And since the remainder of 0 / 2 is 0, it's equivalent to:

if L[i] == 0:

which isn't what you intended.