The modulo operation on negative numbers in Python

前端 未结 8 1933
无人共我
无人共我 2020-11-22 14:26

I\'ve found some strange behaviour in Python regarding negative numbers:

>>> -5 % 4
3

Could anyone explain what\'s going on?

8条回答
  •  一整个雨季
    2020-11-22 14:45

    As pointed out, Python modulo makes a well-reasoned exception to the conventions of other languages.

    This gives negative numbers a seamless behavior, especially when used in combination with the // integer-divide operator, as % modulo often is (as in math.divmod):

    for n in range(-8,8):
        print n, n//4, n%4
    

    Produces:

     -8 -2 0
     -7 -2 1
     -6 -2 2
     -5 -2 3
    
     -4 -1 0
     -3 -1 1
     -2 -1 2
     -1 -1 3
    
      0  0 0
      1  0 1
      2  0 2
      3  0 3
    
      4  1 0
      5  1 1
      6  1 2
      7  1 3
    
    • Python % always outputs zero or positive*
    • Python // always rounds toward negative infinity

    * ... as long as the right operand is positive. On the other hand 11 % -10 == -9

提交回复
热议问题