Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Python 2.6.4 and Python 3.1.2 integer handling

Why does

x = 15
if (x/2) * 2 == x:
    print 'Even'
else: print 'Odd'

Evaluate to Odd in Python 2.6.4?

While in 3.1.2 (with parentheses around print statements of course) is evaluates to Even?

like image 748
Sultan Shakir Avatar asked Jan 26 '26 11:01

Sultan Shakir


1 Answers

In Python 2.x, the / operator uses integer division by default. Since Python 3.x (or if you start your 2.x program with from __future__ import division), the / operator performs floating-point division. This is documented in PEP238.

You should use // if you want integer division, or start your programs with from __future__ import division if you want floating point division under 2.x.

Note that the generic way to check whether a number is even or odd is modulo division with the % operator; like this:

x = 15
print ('even' if x % 2 == 0 else 'odd')

For details on these and other operators, refer to the Python manual.

like image 101
phihag Avatar answered Jan 29 '26 12:01

phihag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!