Reputation: 21
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?
Upvotes: 1
Views: 17185
Reputation: 43504
The part that is raising the exception is int(c)
:
c = "21.1"
print(int(c))
# ValueError: invalid literal for int() with base 10: '21.1'
One minor change would fix this for you:
c="21.1"
try:
float(c)
if "." not in c: #<---- check if "." is in the string c AFTER conversion to float
print("Sorry integers don't have length")
else:
print("Sorry floats don't have length")
except:
print(len(c))
# Sorry floats don't have length
However, it's generally bad practice to blindly catch all exceptions. This would have the unintended side effect of any error in your program triggering the except
block.
It would be more appropriate to catch only the one you are expecting.
c="21.aakdjs1"
try:
float(c)
if "." not in c:
print("Sorry integers don't have length")
else:
print("Sorry floats don't have length")
except ValueError:
print(len(c))
# 10
For future debugging, you can always print the exception.
Upvotes: 0
Reputation: 12684
Input results to a string format so convert the string into float Then check if it is an integer. Change your code into:
old: if float(c) ==int(c):
new: if c.isdigit():
UPDATED:
enter a string: 21.0
Sorry floats don't have length
Upvotes: 0
Reputation: 11232
Also, why not apply the EAFP principle (What is the EAFP principle in Python?) to the second condition, too?
s = input("Input: ")
try:
float(s)
try:
int(s)
print("Sorry, you have entered an integer.")
except:
print("Sorry, you have entered a float.")
except:
print(len(s))
I have omitted to check for ValueError
as the exception, because you didn't check that in your code, too. However, you should have a look at How to properly ignore exceptions
Upvotes: 1