isinstance(raw_input("number: ")), int)
always yields False
because raw_input
return string object as a result.
Use try: int(...) ... except ValueError
:
number = raw_input("number: ")
try:
int(number)
except ValueError:
print False
else:
print True
or use str.isdigit
:
print raw_input("number: ").isdigit()
NOTE The second one yields False
for -4
because it contains non-digits character. Use the second one if you want digits only.
UPDATE As J.F. Sebastian pointed out, str.isdigit
is locale-dependent (Windows). It might return True
even int()
would raise ValueError for the input.
>>> import locale
>>> locale.getpreferredencoding()
'cp1252'
>>> '\xb2'.isdigit() # SUPERSCRIPT TWO
False
>>> locale.setlocale(locale.LC_ALL, 'Danish')
'Danish_Denmark.1252'
>>> '\xb2'.isdigit()
True
>>> int('\xb2')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '\xb2'
number = int(number)
– Pirbhai