How to calculate a mod b in Python?

后端 未结 7 1260
迷失自我
迷失自我 2020-12-12 21:47

Is there a modulo function in the Python math library?

Isn\'t 15 % 4, 3? But 15 mod 4 is 1, right?

相关标签:
7条回答
  • 2020-12-12 21:50
    >>> 15 % 4
    3
    >>>
    

    The modulo gives the remainder after integer division.

    0 讨论(0)
  • 2020-12-12 21:57

    mod = a % b

    This stores the result of a mod b in the variable mod.

    And you are right, 15 mod 4 is 3, which is exactly what python returns:

    >>> 15 % 4
    3
    

    a %= b is also valid.

    0 讨论(0)
  • 2020-12-12 22:00

    I don't think you're fully grasping modulo. a % b and a mod b are just two different ways to express modulo. In this case, python uses %. No, 15 mod 4 is not 1, 15 % 4 == 15 mod 4 == 3.

    0 讨论(0)
  • 2020-12-12 22:03

    There's the % sign. It's not just for the remainder, it is the modulo operation.

    0 讨论(0)
  • 2020-12-12 22:05
    A = [3, 1, 2, 4]
    for a in A:
        print(a % 2)
    

    output:

    1
    1
    0
    0
    
    0 讨论(0)
  • 2020-12-12 22:07

    you can also try divmod(x, y) which returns a tuple (x // y, x % y)

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