What is the result of % in Python?

前端 未结 19 1688
粉色の甜心
粉色の甜心 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:33

    x % y calculates the remainder of the division x divided by y where the quotient is an integer. The remainder has the sign of y.


    On Python 3 the calculation yields 6.75; this is because the / does a true division, not integer division like (by default) on Python 2. On Python 2 1 / 4 gives 0, as the result is rounded down.

    The integer division can be done on Python 3 too, with // operator, thus to get the 7 as a result, you can execute:

    3 + 2 + 1 - 5 + 4 % 2 - 1 // 4 + 6
    

    Also, you can get the Python style division on Python 2, by just adding the line

    from __future__ import division
    

    as the first source code line in each source file.

    0 讨论(0)
提交回复
热议问题