What does %=mean?

Asked

Viewed 8,338 times

12

I have a code that contains the situation below:

id %= 1000

But I don’t know the function of that operator.

3 answers

14


It is the compound operator of assignment and calculation of the module (getting the rest of the division). Essentially it is the same as saying:

id = id % 1000

This is splitting up id by 1000, and assigning the rest obtained to the id.

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

I speak mainly because there are languages that this is not an absolute truth, the semantics may be a little different in some cases.

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

So before you think it’s exactly the same thing, see the compiler/interpreter implementation of your language.

1

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

>>> divmod(3, 2)
(1, 1)
>>> 

-1

It would be the rest of the division:

  1. (1 % 3) = 1
  2. (1 % 5) = 1
  3. (1 / 3) = 1.5
  4. (1 / 5) = 2.5
  • 4

    1 divided by 5 gives 2.5?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.