Why does the following evaluate to a ValueError in python?

520 views Asked by At

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?

3

There are 3 answers

0
Personman On BEST ANSWER

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.

0
Yosafat Vincent Saragih On

I think x = int(5.5) didn't lead to any value error. First problem is, yeah, you cannot directly compare it an input result with int or float. To make sure it let's do this little experiment:

>>> x = input()
>>? 20
>>> print(type(x))
>>> <class 'str'>

From this experiment, you see that even you enter "any numerical" to input, it will return your input as string. And let's check what's going on with int(input()) operation:

    x = int(input())
    5.5
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.5'

This problem happen when you try to 'directly' convert a float to integer. Python cannot convert literally float to int directly. There's another trick to help this, by assign float as the number original datatype. This is happen when and let's see if we add float as another parser :

x = int(float(input()))
5.5
print(type(x))
<class 'int'>

The solution is simple, just directly parse your input as int, then compare it:

x = int(float(input()))
if x == 5 or x == int(5.5):
    #do something

Hope it will help you. Good Luck!

0
darkprinx On

Its because of input() takes the value as a string data type. When you are taking "5" then converting into int() works but converting string input "5.5" to int() will give error as this is not supported by python. In such a case, you have to first convert it to float() and then int() to get an integer value.