Butters Butters - 2 months ago 15
Python Question

int(x)- Is x numeric/non-numeric string?

In the code below,

int(x)
throws an exception. I understand that
x
should be a string but -numeric or non-numeric string?

def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain numbers\n", Argument

# Call above function here.
temp_convert("xyz")

Answer

The string you supply as the function argument has to be representable as an integer. What would you consider the numerical representation of "xyz" to be?

If you pass the function string representations of numbers, positive or negative, then you won't trigger the exception.

When numbers are encoded as strings there are no problems,

>>> int("10")
10
>>> int("-10")
-10

When symbols that aren't readily represented by a number is supplied to the function the exception will triggered,

>>> int("-10a")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '-10a'

int(x) does not accept floating-point numbers either:

>>> int("10.0")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '10.0'
Comments