Python traps · Python
Python: -7 // 2 = -4?!PRO
// rounds DOWN (towards minus infinity), so -3.5 becomes -4. int(-7 / 2) rounds towards zero.
# -7 // 2 = -4 ?! # // is FLOOR division: it rounds DOWN (towards minus infinity), not towards zero. print(-7 // 2) # -4 ?! (-3.5 rounded down is -4) print(7 // 2) # 3 (3.5 rounded down is 3) # Fix: drop the fraction instead (round towards zero) print(int(-7 / 2)) # -3 ✓ import math print(math.trunc(-7 / 2)) # -3 ✓Open code P9 in Pocket Compiler Download the Pocket Compiler app — free
No app yet? Install it, then open the app and type the code P9 in Code Library.