Roshan - 3 years ago 122

Python Question

why does python floor division operator behaves like this?

I came across this code snippet and result was quite surprising.

`a = 1 // 10`

b = -1 // 10

print a,b

a= 0

b=-1

printing output obtained results are

`a=0`

`b= -1`

why does

`a=0`

`b= -1`

`//`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

`//`

in Python is a "floor division" operator. That means that the result of such division is the floor of the result of regular division (performed with / operator).

The floor of the given number is the biggest integer smaller than the this number. For example

`7 / 2 = 3.5`

so `7 // 2 = floor of 3.5 = 3`

.

For negative numbers it is less intuitive: `-7 / 2 = -3.5`

, `so -7 // 2 = floor of -3.5 = -4`

. Similarly `-1 // 10 = floor of -0.1 = -1`

.

`//`

is defined to do the same thing as `math.floor()`

: return the largest integer value less than or equal to the floating-point result. **Zero is not less than or equal to -0.1.**

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**