16

Is there a method that I can use to check if a raw_input is an integer?

I found this method after researching in the web:

print isinstance(raw_input("number: ")), int)

but when I run it and input 4 for example, I get FALSE. I'm kind of new to python, any help would be appreciated.

falsetru
  • 357,413
  • 63
  • 732
  • 636
Alejandro Veintimilla
  • 10,743
  • 23
  • 91
  • 180

5 Answers5

24

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'
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • Or, if they want to turn the variable into a number, `number = int(number)` – SethMMorton Oct 18 '13 at 03:16
  • 1
    `str.isdigit()` may depend on locale (because Microsoft) i.e., it might return `True` even `int()` would raise ValueError for the input. – jfs Oct 19 '14 at 05:13
  • @J.F.Sebastian, `raw_input()` returns a `str` object, not an `unicode` object. So I think `str.isdigit` will work as expected. Could you give me an example. – falsetru Oct 19 '14 at 05:34
  • [`str.isdigit()`](https://docs.python.org/2/library/stdtypes.html?highlight=str.isdigit#str.isdigit): *"For 8-bit strings, this method is locale-dependent."*. – jfs Oct 19 '14 at 05:42
  • `'\xb2'.isdigit()` might be true on Python 2 if locale uses cp1252 character encoding (on Windows). – jfs Oct 19 '14 at 05:45
  • @J.F.Sebastian, Thank you for the information. I am trying to reproduce it myself. I'll update the answer as soon as I reproduce it. – falsetru Oct 19 '14 at 05:47
  • @J.F.Sebastian, I updated answer according to you. BTW, I couldn't reproduce it. http://i.imgur.com/pHvgZOY.png . Could you give me any hint? I'm ready to change language/locale and reboot ;) – falsetru Oct 19 '14 at 06:12
  • 1
    use cp1252 locale, not cp1251. PYTHONIOENCODING is unrelated. – jfs Oct 19 '14 at 06:19
  • @J.F.Sebastian, I could reproduce it thanks to you. Nice to know it. Going back to my original langauge :) – falsetru Oct 19 '14 at 06:30
  • have you checked that `int('\xb2')` raises `ValueError` in Danish locale? – jfs Oct 19 '14 at 06:40
  • 1
    @J.F.Sebastian, Yes, I checked it: http://i.imgur.com/BglM8Ol.png . I forgot to paste that part. Thank you again :) – falsetru Oct 19 '14 at 06:47
8

You can do it this way:

try:
    val = int(raw_input("number: "))
except ValueError:
    # not an integer
Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
1

Try this method .isdigit(), see example below.

user_input = raw_input()
if user_input.isdigit():
    print "That is a number."

else:
    print "That is not a number."

If you require the input to remain digit for further use, you can add something like:

new_variable = int(user_input)
Elf Machine
  • 73
  • 1
  • 4
0

here is my solution

`x =raw_input('Enter a number or a word: ')
y = x.isdigit()
if (y == False):
    for i in range(len(x)):
        print('I'),
else:
    for i in range(int(x)):
        print('I'),

`

  • Please consider editing your post to explain how this works as code only answers don't always make it clear to the OP how to resolve their issue. – SuperBiasedMan Sep 12 '15 at 13:58
0
def checker():
  inputt = raw_input("how many u want to check?")
  try:
      return int(inputt)
  except ValueError:
      print "Error!, pls enter int!"
      return checker()
tuomastik
  • 4,559
  • 5
  • 36
  • 48
Frank Musterman
  • 642
  • 1
  • 7
  • 14