-1

I'm solving some coding challenges on CoderByte and unfortunately they provide Python2. One thing I noticed is that the round() function is giving different outputs on python3 and python2. When i write this on python 2:

print int(round(100/60))

I get output of 1 (please explain why)

But on python 3 the same command gives 2 which is correct.

hjjinx
  • 55
  • 6
  • 1
    I posted a new question because I didn't know the problem. Now that I know the problem, I know that this has already been answered. Some other person might have the same problem and search for this. He can find the answer here. – hjjinx Jun 17 '18 at 19:29

2 Answers2

1

In python 2 the divide operator on integers returns integer, so 100/60==1. This unintuitive C-like behaviour was changed in python 3.

To make this code work properly in python 2 you should convert one of the integers to float: print int(round(100/60.)), that . means 60.0.

Andrew Morozko
  • 2,576
  • 16
  • 16
0

The problem is not the rounding, but the interpretation of /.

In python 2 if dividing 2 integers with / you get an integer not a float.

In python 3 you get a float if you use / - the "pure" integer division is done by using //.

Python 2:

print(100/60) # ==> 1
print(100/60.0) # ==> 1.6666666666...

Python 3:

print (100/60) # ==> 1.6666
print (100//60) # ==> 1

They both get rounded accordingly, but if you input a 1 into round, it will result in 1.

You can read more about the reason for the changed behaviour here: PEP 238

The current division (/) operator has an ambiguous meaning for numerical arguments: it returns the floor of the mathematical result of division if the arguments are ints or longs, but it returns a reasonable approximation of the division result if the arguments are floats or complex. This makes expressions expecting float or complex results error-prone when integers are not expected but possible as inputs.

We propose to fix this by introducing different operators for different operations: x/y to return a reasonable approximation of the mathematical result of the division ("true division"), x//y to return the floor ("floor division"). We call the current, mixed meaning of x/y "classic division".

Community
  • 1
  • 1
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69