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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With