What is the result of % in Python?

前端 未结 19 2052
粉色の甜心
粉色の甜心 2020-11-22 00:57

What does the % in a calculation? I can\'t seem to work out what it does.

Does it work out a percent of the calculation for example: 4 % 2

19条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 01:15

    It was hard for me to readily find specific use cases for the use of % online ,e.g. why does doing fractional modulus division or negative modulus division result in the answer that it does. Hope this helps clarify questions like this:

    Modulus Division In General:

    Modulus division returns the remainder of a mathematical division operation. It is does it as follows:

    Say we have a dividend of 5 and divisor of 2, the following division operation would be (equated to x):

    dividend = 5
    divisor = 2
    
    x = 5/2 
    
    1. The first step in the modulus calculation is to conduct integer division:

      x_int = 5 // 2 ( integer division in python uses double slash)

      x_int = 2

    2. Next, the output of x_int is multiplied by the divisor:

      x_mult = x_int * divisor x_mult = 4

    3. Lastly, the dividend is subtracted from the x_mult

      dividend - x_mult = 1

    4. The modulus operation ,therefore, returns 1:

      5 % 2 = 1

    Application to apply the modulus to a fraction

    Example: 2 % 5 
    

    The calculation of the modulus when applied to a fraction is the same as above; however, it is important to note that the integer division will result in a value of zero when the divisor is larger than the dividend:

    dividend = 2 
    divisor = 5
    

    The integer division results in 0 whereas the; therefore, when step 3 above is performed, the value of the dividend is carried through (subtracted from zero):

    dividend - 0 = 2  —> 2 % 5 = 2 
    

    Application to apply the modulus to a negative

    Floor division occurs in which the value of the integer division is rounded down to the lowest integer value:

    import math 
    
    x = -1.1
    math.floor(-1.1) = -2 
    
    y = 1.1
    math.floor = 1
    

    Therefore, when you do integer division you may get a different outcome than you expect!

    Applying the steps above on the following dividend and divisor illustrates the modulus concept:

    dividend: -5 
    divisor: 2 
    

    Step 1: Apply integer division

    x_int = -5 // 2  = -3
    

    Step 2: Multiply the result of the integer division by the divisor

    x_mult = x_int * 2 = -6
    

    Step 3: Subtract the dividend from the multiplied variable, notice the double negative.

    dividend - x_mult = -5 -(-6) = 1
    

    Therefore:

    -5 % 2 = 1
    

提交回复
热议问题