inputs: 'aa'
, '22'
, '2.45'
input ='22'
try:
print int(input)
except ValueError:
print float(input)
How to handle the above code when the input is 'aa' or 'example'?
inputs: 'aa'
, '22'
, '2.45'
input ='22'
try:
print int(input)
except ValueError:
print float(input)
How to handle the above code when the input is 'aa' or 'example'?
I think that the simplest way to handle this is to check if the input string is numeric first:
https://www.tutorialspoint.com/python/string_isnumeric.htm
if input.isnumeric():
print int(input)
else:
try
print float(input)
except ValueError:
# Do nothing
However if you can avoid exceptions completely the code would be better - exception handling can be quite expensive.
This answer to testing for an integer explains why exception handling can be expensive: https://stackoverflow.com/a/9859202/8358096
To avoid the second exception being hit regularly you could use the isalpha function mentioned below.
if input.isnumeric():
print int(input)
else:
if not input.isalpha():
try
print float(input)
except ValueError:
# Do nothing
s = 'aa'
try:
print int(s)
except ValueError:
try:
print float(s)
except:
print 'its is a string'
You should use str.isalpha
The only time this breaks in cases like input = 'a2'
.
inputs = ['aa','22','2.45']
for input in inputs:
if not input.isalpha():
try:
print int(input)
except ValueError:
print float(input)