+ 2
Int function and decimal number
Dear friends, I wonder why the following code when the input is a decimal number will not work. x = int (input ("Enter a number: ")) print(x) when e.g. you put 123.97, it returns an error! I suppose it gives back 123 just as the int(123.97) does when written directly in the IDLE, but it does not. I cannot understand the error. Could any of you kindly help me to find the answer?
8 Answers
+ 1
when converting from a string, you need the exact conversion. if the string is "173.99", you would use float(). if the string is "82", you would use int ()
(or float (), but then you would get 82.0).
so since the string has a decimal, you need to use float () first, and then in a second line you can convert it using int ()
+ 1
cause int( ) means you are trying to convert the string to a integer, but if its not an integer (like 123.97 which is a float), it will cause an error.
+ 1
x = float(input ("Enter a number: "))
print(int(x))
try this instead
+ 1
x = float(input ("Enter a number: "))
int(x)
print(x)
it has to be done in two steps. first the proper string conversion, then you can cut off the decimal my converting the floating point number to an integer.
still have doubts?
+ 1
no problem buddy
0
Dear Edward, thank for your reply. But, why it does not give any error when running int(123.97) directly in the IDLE?
The error says something about "int base in 10"
0
Dear Edward. I know this code. I just wonder why the error should come up? Why float() does not give back the error?
0
Thank you for your kind response Edward. :)