Home > Blockchain >  Python Beginner problems
Python Beginner problems

Time:11-26

So I was writing a code of reversing a number in python :-

def intreverse(n):
  m= 0
  while n>0:
    (d,n)= (n%10,n/10)
    m= 10*m   d 
  return(m)
print(intreverse(45))

I got my results but I was wondering , since in python3 we get a float number.But why not in the above case. Like If I take n=45 , then updating the n:=4.5 but python consider it as 4 . why though ?? please clarify the doubt of this noob.

CodePudding user response:

In Python 2 the division between two integers is interpreted as an integer division that returns an integer (as does //). However if one of the two numbers involved in the division is a float, then the operator is interpreted as the float division which returns a float.

In Python 3 the behavior of / has been made the same regardless of the type of the numbers involved so you will get a float no matter what, and the integer division is still //.

For example in Python 3 you have:

>>> 45/10
4.5
>>> 40/10
4.0
>>> 45//10
4

But in Python 2 you have:

>>> 45/10
4
>>> 40/10
4
>>> 45.0/10
4.5
>>> 45//10
4
  • Related