Member-only story

Python — Why is there a difference between `0–3//2` and ` — 3//2`?

How to do floor/ceiling operations without the math module

Flutter Developer
1 min readOct 17, 2021

Python uses the symbol - as both a unary (-x) and a binary (x-y) operator. These have different operator precedence.

In specific, the ordering wrt // is:

  • unary -
  • binary //
  • binary -

By introducing a 0 as 0--3//2, the first - is a binary - and is applied last. Without a leading 0 as --3//2, both - are unary and applied together.

The corresponding evaluation/syntax tree is roughly like this, evaluating nodes at the bottom first to use them in the parent node:

---------------- ---------------- 
|     --3//2     |    0--3//2     |
|================|================|
|                |    -------     |
|                |   | 0 - z |    |
|                |    -----+-     |
| | | |
|     --------   |     ----+---   |
|    | x // y |  |    | x // y |  |
|     -+----+-   |     -+----+-   |
| | | | | | |
|  ----+    +--  |   ---+    +--  |
| | --3 |  | 2 | |  | -3 |  | 2 | |
|  -----    ---  |   ----    ---  |
---------------- ----------------

Because the unary - are applied together, they cancel out. In contrast, the unary and binary - are applied before and after the division, respectively.

--

--

Flutter Developer
Flutter Developer

Written by Flutter Developer

Flutter and Native Android developer

Responses (1)