0

I am new to Python3 and facing this particular issue. I want 6/2 to give an answer of 3 instead of 3.0, but at the same time i want 7/2 to give me 3.5 On using '//' it converts all the float values to integer values.

adsbawston
  • 55
  • 1
  • 1
  • 5

1 Answers1

1

You could check if the result has a value after the decimal point and cast to an integer or float depending on that.

num = a / b
if int(num) - num == 0:
    num = int(num)
else:
    num = float(num)

The second part is technically redundant, but I left it there for the sake of completeness.

This question is also a duplicate: How to check if a float value is a whole number

Community
  • 1
  • 1
Hal T
  • 527
  • 7
  • 22