简体   繁体   中英

python basic code printed differently

[Basically the professor from the video is testing the exact same basic code but his one is printed is "Odd" while my python program is printed "Even" which should be printed "Even" why it is printed differently when using the exact same code?

The video link is here https://youtu.be/Pij6J0HsYFA?t=1942 ] 1

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

Integer division behaves differently in Python 2.7 and Python 3.X.

C:\Users\Kevin\Desktop>py -2
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 15/2
7
>>> (15/2)*2
14
>>> ^Z


C:\Users\Kevin\Desktop>py -3
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 15/2
7.5
>>> (15/2)*2
15.0
>>>

The professor is probably using 2.7, and you're probably using 3.X.

In any case, it's much better to use modulus to check the evenness of a number, since it doesn't depend on version-specific behavior.

>>> def is_even(x):
...     return x%2 == 0
...
>>> is_even(15)
False
>>> is_even(16)
True
>>> is_even(17)
False

Because the lecturer is using Py2 and you are using Py3.

In Python 2, the result of dividing integers is an integer, which gets truncated: 15 / 2 == 7 . Since 7 * 2 != 15 , the lecturer prints Odd .

In Python 3, the result of dividing integers is a float if need be to preserve the actual value: 15 / 2 == 7.5 , so you print Even .

The equivalent Py3 operation to preserve the type and floor the result would be 15 // 2 == 7 .

The difference is due to Python2 and Python3.

In Python 3.0, 5 / 2 will return 2.5 .The same in Python2 would generate 2.

The former being floating point division and other integer division.

In the code you mentioned, (15/2)*2 is 14 as 7 is being generated as floor value not 7.5 which is not equal to 15.Hence it will print Odd ,due to python2 .

On the other hand,your code will generate (15/2)*2 as 15 due to floating point precision and hence print Even. due to python3 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM