0

When running code:

integer = input("Enter an integer: ")
try:
    int(integer)
    print("Good work!")
except ValueError:
    print("Thats not an integer")

Why does entering a float like 5.8 get to the except clause yet int(5.8) is 5 and doesn't raise a ValueError?

Tim
  • 63
  • 7
  • 1
    Or [this](https://stackoverflow.com/questions/17557870/python-invalid-literal-for-int-with-base-10-808-666666666667)? – costaparas Feb 20 '21 at 04:49

2 Answers2

1

A float will always be considered a ValueError if input where an integer is expected. However, inputting int(5.8) will not cause an error because the code changes the value from 5.8 to 5 before the code tests to see if it is a valid input. Therefore, 5.8 will cause an error and int(5.8) will not.

1

When you enter a float, what you are doing is int("5.8") which is not valid because it is a string here, you cannot convert floats inside strings to integers, so first convert it to a float, then an int int(float(integer))

Vinam
  • 66
  • 1
  • 3