0

Consider this expression 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6.

DuckDuckGo evaluates it to 6.75 (as does Google).

Python 2 evaluates it to 7:

$ python
Python 2.7.5 (default, Mar  9 2014, 22:15:05) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
7
>>> ^D

Python 3 evaluates it to 6.75:

$ python3
Python 3.4.0 (default, Apr  9 2014, 11:51:10) 
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
6.75
>>>`enter code here`

Why does Python 2 evaluate to 7 and Python 3 evaluate to 6.75?

How does Python arrive at the result?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
unpossible
  • 303
  • 1
  • 8
  • 20

2 Answers2

3

In py2, 1/4->0 for integers, in py3 1/4->0.25. You can use explicit true division in py2

3 + 2 + 1 - 5 + 4 % 2 - 1. / 4 + 6  # note the decimal point

or you can do a

from __future__ import division

to use the py3 behaviour.

mdurant
  • 27,272
  • 5
  • 45
  • 74
  • Could you perhaps add how one can "use explicit true division"? – jonrsharpe Jul 23 '14 at 20:19
  • Either have a real number (as the answer below), or use numpy.true_divide(1,4) (this is overkill). Note that the operator // does the opposite and produces a whole number, 7.//2.->3. – mdurant Jul 23 '14 at 20:27
  • Yes, *I* know that, I'm suggesting you *edit the question* to include this information. – jonrsharpe Jul 23 '14 at 20:28
0

Integer division in Python 2.x truncates.

Python did not forget how to do math, you just need to give it more instructions sometimes. If you make a simple change to the expression

print 3 + 2 + 1 - 5 + 4 % 2 - 1.00 / 4 + 6

You should get your 6.75

tyh
  • 977
  • 1
  • 8
  • 22