DEV Community

DR
DR

Posted on

3 2

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!

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay