How // And % Work With Negative Numbers In Python eg. ( 37 % -10 )

Liu Zuo Lin
3 min readAug 29, 2024

Disclaimer — this will probably not be useful in real life. I read up on this because I’ll be tested on this during an exam (and it’s kinda fun to learn how things work in the backend)

To understand how % (modulo) works, we need to first understand how // (floor divide) works.

How // (floor divide) works

Finding 37 // 10

  • let’s first look at true division. 37 / 10 is 3.7
  • the floor of 3.7 is 3
  • 37 // 10 is thus 3 (floor division)

How // works for negative numbers

Finding 37 // -10

  • let’s first look at true division. 37 / -10 is -3.7
  • the floor of -3.7 is -4 (notice that it rounds leftwards)
  • 37 // -10 is thus -4

Finding -37 // 10

  • let’s first look at true division. -37 / 10 is -3.7
  • the floor of -3.7 is -4
  • -37 // 10 is thus -4

Finding -37 // -10

  • let’s first look at true division. -37 / -10 is 3.7
  • the floor of 3.7 is 3
  • -37 // -10 is thus 3

--

--

Liu Zuo Lin
Liu Zuo Lin

No responses yet