2

I (really, really) need division operator in Python3 behaves like in Python2.

Python2 code:

--> 11/5
2
--> 11.0/5
2.2

But in Python3 we have

--> 11//5
2
--> 11.0//5
2.0

I can change / to // or whatever, but I expect the same results. Any ideas?

4
  • 6
    You can't make the Python 3 / operator behave like the Python 2 one. If you want integer division is Python 3, you must use //. There is no way to get an operator in Python 3 that sometimes does integer division and sometimes does float division; the whole point of changing this in Python 3 was to cleanly separate those two operations. You would need to write your own function that checks the types and uses the operator you want. Commented May 30, 2014 at 7:28
  • Do you really need one operator that does floor division for ints and true division for floats, or can you use the appropriate operator for the appropriate types? Commented May 30, 2014 at 7:29
  • I really need that feature because my css preprocessor serves arithmetic operations to users by eval(). And for CSS that behavior was perfect: VALUE_IN_PIXELS/2 -> integer, FLOAT_VALUE_IN_EM -> float Commented May 30, 2014 at 16:06
  • ".. by eval()". Bzzz. Fix that. Commented Jan 29, 2020 at 0:07

2 Answers 2

5

You can't make it work like that. You'll have to use / and // when appropriate.

If, for some reason, you need the "polymorphism" of the old operator, you can...

def div(a, b):
    if isinstance(a, int):
        return a // b
    else:
        return a / b
Sign up to request clarification or add additional context in comments.

2 Comments

OK. Because it's not possible, I just truncate result when input was all integers. I mean input of my arithmetic calculator which is provide by eval() in one css preprocessor I'm developing.
and in python2 i use import future
0

You can use this code, for support of your old code. It works with other keywords too.

from __future__ import division

I hope it helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.