Reputation: 31
When I ran the following Python code, I got different results using Python 2.7 and Python 3.4, I have no idea why...
import sys
def main():
total = 0
number = 568
while number:
total += number % 10
print("total = %d" % total)
number /= 10
if __name__ == '__main__':
main()
Output result using Python 2.7:
total = 8
total = 14
total = 19
Output result using Python 3.4(I deleted some output because it's too long):
total = 8
total = 14
total = 20
total = 21
total = 21
total = 21
..........
Upvotes: 2
Views: 47
Reputation: 178254
Python 2.X implements integer division, so 568 / 10 = 56.
Python 3.X implements true division, so 568 / 10 = 56.8.
Change "total = %d"
to "total = %f"
to see the difference.
To force integer division, use //
instead of /
.
To make Python 2 work like Python 3, add from __future__ import division
to the top of the script.
Upvotes: 3