'Why doesn't the int() function convert a float to integer while in input() function?
Why doesn't the int() function convert a float to integer while in input() function?
input_1 = input(f'enter the num: ')
try:
a = int(input_1)
print(f"it is an integer")
except:
print(f"no an integer")
input_1 = 3.532453
try:
a = int(input_1)
print(f"it is an integer")
except:
print(f"no an integer")
Result:
enter the num: 3.532453
no an integer
it is an integer
Solution 1:[1]
Bear in mind that the input_1 value when you request for an input is not a float, is a string
input_1 = input(f'enter the num: ')
print(type(input_1)) # ?<class 'str'>
So with the cast you are trying to convert a string with value 3.532453 into a integer.
If you cast this string to a float first and then you cast it into a integer, it will work.
input_1 = input(f'enter the num: ')
try:
a = int(float(input_1))
print(f"it is an integer")
except:
print(f"no an integer")
Solution 2:[2]
The input function returns a string (type str in python). The int function accepts a string as long as this string represents a valid integer (base 10 by default). This means when you pass a string that contains a ., int will fail because the string is not a valid integer.
>>> input_1 = input(f'enter the num: ')
enter the num: 3.532453
>>> print(type(input_1))
<class 'str'>
>>> int(input_1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '3.532453'
On the other hand, when you do input_1 = 3.532453, you are creating a variable input_1 of type float. The int function accepts float arguments and casts them to integer by stripping the floating point part.
>>> input_1 = 3.532453
>>> print(type(input_1))
<class 'float'>
>>> int(input_1)
3
Solution 3:[3]
print(int(123.456)): you can convert a non-integer to int
print(int("123456")): you can convert a string representing an integer to int
print(int("123.456")): you cannot convert a string representing a non-integer to int
I mean, you can, but not by using the int(...) operation directly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Latra |
| Solution 2 | alih |
| Solution 3 | bbbbbbbbb |
