I want to ask the user to input a value and then print its length, if the input is a string. If the user's input is an integer or a decimal, I want to print "Sorry, integers don't have length"
or "Sorry, floats don't have length"
, respectively.
I'm making use of exception while trying to convert the input into float or integer.
Here is my code:
c=input("enter a string: ")
def length(c):
return len(c)
try:
float(c)
if float(c)==int(c):
print("Sorry integers don't have length")
else:
print("Sorry floats don't have length")
except:
print(length(c))
The output results are as follows:
> enter a string: sfkelkrelte
11
> enter a string: 21
Sorry integers don't have length
> enter a string: 21.1
4
When I input an integer, the error message is displayed correctly, as the conversion float() is possible. But, in case of a floating point number, the interpreter goes to except
block, though it should have executed the try
block.
Why does this happen?