What does% = mean?

12

I have a code that contains the situation below:

id %= 1000

But I do not know the function of this operator.

    
asked by anonymous 19.11.2015 / 13:48

3 answers

14

It is the composite assignment and calculation operator of the module (obtaining the remainder of the division). Essentially it's the same as saying:

id = id % 1000

This is dividing id by 1000, and assigning the remainder obtained to id itself.

Compound operators perform an operation followed by an assignment. The operation is the first character before the equal sign.

I said essentially because it has languages that this is not an absolute truth, the semantics may be a bit different in some cases.

Some people think this is just syntactic sugar, and in most cases nowadays it is, but not always, and in the past it was different. Today it is usually just a contracted form of writing, but it was common for this operator to offer more performance than the extensive form since compilers did not usually do many optimizations.

Then before you find that it's exactly the same thing, check out the compiler / interpreter implementation of your language.

    
19.11.2015 / 13:52
1

There is also the function divmod, which returns the result of the division and the rest of it.

>>> divmod(3, 2)
(1, 1)
>>> 
    
25.11.2015 / 02:20
-1

It would be the rest of the division:

  • (1 % 3) = 1
  • (1 % 5) = 1
  • (1 / 3) = 1.5
  • (1 / 5) = 2.5
  • 31.03.2016 / 16:16