DEV Community

DR
DR

Posted on

Division vs. Integer Division

Hi everyone! Found another cool trick relating to division in Python. I was testing some things and came upon a script that produced an error even though I didn't think it should've.

for x in range(0, 42/6):
  print(x)
Enter fullscreen mode Exit fullscreen mode

Turns out that Python doesn't like when a floating-point number is used in a range. And this led me to my first discovery, that the Python division operator always returns a floating-point value. So in my script, it was returning 8.0 instead of my desired 8.

So how to get the 8? Well, let's turn to the Python floor division operator (//). This returns an integer value, and it's helpful for when we're dividing two numbers that we know will divide cleanly. If they don't divide cleanly, it returns the cleanly floored value (8.8 rounds to 8, 7.3 to 7 and so on). This is so that it's always able to return a non-floating integer. So my original code updates to the following.

for x in range(1, 42//6): # returns 8!
  print(x)
Enter fullscreen mode Exit fullscreen mode

In conclusion:
/: returns a floating point representing the number on the left divided by the number on the right
//: returns an integer representing the floor of the number on the left divided by the number on the right

Make sure to follow for more JS/Python code tidbits!

Top comments (0)