Search code examples
pythonintegervalueerror

Why does the following evaluate to a ValueError in python?


We were coding something awhile ago and we came across a small problem. We wanted to try to convert float numbers to integers

Here is the code:

x = int(input(())
print x

We tried the code and put 5.5. It evaluated to a ValueError. Logically, it is sound in logic. But if we try the following code:

x = int(float(input(())) OR x = int(5.5), it evaluates to a value of 5.

Why does this happen?


Solution

  • In the first case, you are calling int("5.5"), because input() returns a string. that's a ValueError because 5.5 is not an int, and the designers of python decided not to do any implicit casting.

    In the second case, you care calling float("5.5"), which is 5.5 because "5.5" can be converted to a float as you asked, and then int(5.5), which is the result of converting a float to an int (python uses truncation for this; you can call round() instead if that's not what you want).

    The third case is just the same as the second step of the second case.