167

How do I check if a user's string input is a number (e.g. -1, 0, 1, etc.)?

user_input = input("Enter something:")

if type(user_input) == int:
    print("Is a number")
else:
    print("Not a number")

The above won't work since input always returns a string.

Trevor Boyd Smith
  • 16,711
  • 29
  • 116
  • 163
Trufa
  • 38,078
  • 41
  • 121
  • 186

28 Answers28

291

Simply try converting it to an int and then bailing out if it doesn't work.

try:
    val = int(userInput)
except ValueError:
    print("That's not an int!")

See Handling Exceptions in the official tutorial.

wjandrea
  • 23,210
  • 7
  • 49
  • 68
Daniel DiPaolo
  • 53,439
  • 13
  • 112
  • 113
103

Apparently this will not work for negative values, but it will for positive numbers.

Use isdigit()

if userinput.isdigit():
    #do stuff
Chandrahas Aroori
  • 877
  • 2
  • 13
  • 26
jmichalicek
  • 2,318
  • 1
  • 17
  • 7
  • 54
    "-1".isdigit() == False – BatchyX Mar 24 '11 at 19:55
  • 1
    I don't believe so, Llopis. I kind of jumped the gun answering questions before I knew enough back when I gave this answer. I would do the same as Daniel DiPaolo's answer for the int, but use float() instead of int(). – jmichalicek Jan 08 '14 at 18:50
  • 1
    Negative numbers and floats return false because '-' and '.' are not digits. The isdigit() function checks if every character in the string is between '0' and '9'. – Carl H Apr 14 '15 at 09:58
  • 1
    Use `isdecimal` not `isdigit` because `isdigit` is an unsafe test that recognises characters like unicode power-of-2, ² , as a digit that can not be converted to integers. – Dave Rove Jul 16 '20 at 11:45
53

The method isnumeric() will do the job (Documentation for python3.x):

>>>a = '123'
>>>a.isnumeric()
True

But remember:

>>>a = '-1'
>>>a.isnumeric()
False

isnumeric() returns True if all characters in the string are numeric characters, and there is at least one character.

So negative numbers are not accepted.

:):):)

Athrav
  • 3
  • 2
Andrés Fernández
  • 3,015
  • 2
  • 17
  • 21
25

For Python 3 the following will work.

userInput = 0
while True:
  try:
     userInput = int(input("Enter something: "))       
  except ValueError:
     print("Not an integer!")
     continue
  else:
     print("Yes an integer!")
     break 
RazorX
  • 251
  • 3
  • 3
12

EDITED: You could also use this below code to find out if its a number or also a negative

import re
num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$")
isnumber = re.match(num_format,givennumber)
if isnumber:
    print "given string is number"

you could also change your format to your specific requirement. I am seeing this post a little too late.but hope this helps other persons who are looking for answers :) . let me know if anythings wrong in the given code.

karthik27
  • 484
  • 1
  • 4
  • 12
  • This will check if there is a numeric (float, int, etc) within the string. However, if there is more than just the numeric, it will still return a result. For example: "1.2 Gbps" will return a false positive. This may or may not be useful to some people. – Brian Bruggeman May 28 '15 at 19:35
  • 1
    Also note: for anyone now looking, my original comment is no longer valid. :P Thanks for the update @karthik27! – Brian Bruggeman Aug 24 '15 at 14:30
9

If you specifically need an int or float, you could try "is not int" or "is not float":

user_input = ''
while user_input is not int:
    try:
        user_input = int(input('Enter a number: '))
        break
    except ValueError:
        print('Please enter a valid number: ')

print('You entered {}'.format(user_input))

If you only need to work with ints, then the most elegant solution I've seen is the ".isdigit()" method:

a = ''
while a.isdigit() == False:
    a = input('Enter a number: ')

print('You entered {}'.format(a))
Leonardo
  • 741
  • 1
  • 5
  • 21
Woody
  • 91
  • 1
  • 3
6

Works fine for check if an input is a positive Integer AND in a specific range

def checkIntValue():
    '''Works fine for check if an **input** is
   a positive Integer AND in a specific range'''
    maxValue = 20
    while True:
        try:
            intTarget = int(input('Your number ?'))
        except ValueError:
            continue
        else:
            if intTarget < 1 or intTarget > maxValue:
                continue
            else:
                return (intTarget)
5

I would recommend this, @karthik27, for negative numbers

import re
num_format = re.compile(r'^\-?[1-9][0-9]*\.?[0-9]*')

Then do whatever you want with that regular expression, match(), findall() etc

rachit_verma
  • 181
  • 2
  • 6
5

the most elegant solutions would be the already proposed,

a=123
bool_a = a.isnumeric()

Unfortunatelly it doesn't work both for negative integers and for general float values of a. If your point is to check if 'a' is a generic number beyond integers i'd suggest the following one, which works for every kind of float and integer :). Here is the test:

def isanumber(a):

    try:
        float(repr(a))
        bool_a = True
    except:
        bool_a = False

    return bool_a


a = 1 # integer
isanumber(a)
>>> True

a = -2.5982347892 # general float
isanumber(a)
>>> True

a = '1' # actually a string
isanumber(a)
>>> False

I hope you find it useful :)

Martin Tournoij
  • 24,971
  • 24
  • 101
  • 136
5

natural: [0, 1, 2 ... ∞]

Python 2

it_is = unicode(user_input).isnumeric()

Python 3

it_is = str(user_input).isnumeric()

integer: [-∞, .., -2, -1, 0, 1, 2, ∞]

try:
    int(user_input)
    it_is = True
except ValueError:
    it_is = False
 

float: [-∞, .., -2, -1.0...1, -1, -0.0...1, 0, 0.0...1, ..., 1, 1.0...1, ..., ∞]

try:
    float(user_input)
    it_is = True
except ValueError:
    it_is = False
Luis Sieira
  • 25,446
  • 3
  • 30
  • 53
4

You can use the isdigit() method for strings. In this case, as you said the input is always a string:

    user_input = input("Enter something:")
    if user_input.isdigit():
        print("Is a number")
    else:
        print("Not a number")
Raj Shah
  • 668
  • 7
  • 13
4

This solution will accept only integers and nothing but integers.

def is_number(s):
    while s.isdigit() == False:
        s = raw_input("Enter only numbers: ")
    return int(s)


# Your program starts here    
user_input = is_number(raw_input("Enter a number: "))
Salam
  • 808
  • 12
  • 17
3

This works with any number, including a fraction:

import fractions

def isnumber(s):
   try:
     float(s)
     return True
   except ValueError:
     try: 
       Fraction(s)
       return True
     except ValueError: 
       return False
Antoni Gual Via
  • 692
  • 1
  • 6
  • 12
3

Why not divide the input by a number? This way works with everything. Negatives, floats, and negative floats. Also Blank spaces and zero.

numList = [499, -486, 0.1255468, -0.21554, 'a', "this", "long string here", "455 street area", 0, ""]

for item in numList:

    try:
        print (item / 2) #You can divide by any number really, except zero
    except:
        print "Not A Number: " + item

Result:

249
-243
0.0627734
-0.10777
Not A Number: a
Not A Number: this
Not A Number: long string here
Not A Number: 455 street area
0
Not A Number: 
SPYBUG96
  • 957
  • 3
  • 16
  • 35
  • 2
    This only works because your numbers here are numeric types. An input of "8" (type str) would be "Not A Number." – fwip Sep 22 '19 at 20:52
1

I know this is pretty late but its to help anyone else that had to spend 6 hours trying to figure this out. (thats what I did):

This works flawlessly: (checks if any letter is in the input/checks if input is either integer or float)

a=(raw_input("Amount:"))

try:
    int(a)
except ValueError:
    try:
        float(a)
    except ValueError:
        print "This is not a number"
        a=0


if a==0:
    a=0
else:
    print a
    #Do stuff
1

Here is a simple function that checks input for INT and RANGE. Here, returns 'True' if input is integer between 1-100, 'False' otherwise

def validate(userInput):

    try:
        val = int(userInput)
        if val > 0 and val < 101:
            valid = True
        else:
            valid = False

    except Exception:
        valid = False

    return valid
Jesse Downing
  • 186
  • 1
  • 13
  • 1
    Welcome to Stack Overflow! This is an old question, and the accepted answer seems to be pretty good. Are you sure that you have something new to add? – Dietrich Epp Nov 11 '15 at 21:57
  • 1
    I thought it was a slight improvement: no less efficient while avoiding the nested if-else. I'm new here, if the answer hurts the community no hard feels if it's removed. – Jesse Downing Nov 11 '15 at 22:31
1

I've been using a different approach I thought I'd share. Start with creating a valid range:

valid = [str(i) for i in range(-10,11)] #  ["-10","-9...."10"] 

Now ask for a number and if not in list continue asking:

p = input("Enter a number: ")

while p not in valid:
    p = input("Not valid. Try to enter a number again: ")

Lastly convert to int (which will work because list only contains integers as strings:

p = int(p)
Anton vBR
  • 16,833
  • 3
  • 36
  • 44
0

I also ran into problems this morning with users being able to enter non-integer responses to my specific request for an integer.

This was the solution that ended up working well for me to force an answer I wanted:

player_number = 0
while player_number != 1 and player_number !=2:
    player_number = raw_input("Are you Player 1 or 2? ")
    try:
        player_number = int(player_number)
    except ValueError:
        print "Please enter '1' or '2'..."

I would get exceptions before even reaching the try: statement when I used

player_number = int(raw_input("Are you Player 1 or 2? ") 

and the user entered "J" or any other non-integer character. It worked out best to take it as raw input, check to see if that raw input could be converted to an integer, and then convert it afterward.

Luis Sieira
  • 25,446
  • 3
  • 30
  • 53
0

Here is the simplest solution:

a= input("Choose the option\n")

if(int(a)):
    print (a);
else:
    print("Try Again")
Akshay Sahai
  • 1,905
  • 15
  • 20
  • `SyntaxError: 'return' outside function`. Also, `a is int` will never evaluate to `True`. – Nelewout Jan 06 '16 at 20:48
  • thanks @N.Wouda for your help , i have made the changes,check this – Akshay Sahai Jan 06 '16 at 22:31
  • Are you sure that your answer is actually contributing something new to this question? – Nelewout Jan 06 '16 at 22:39
  • @N.Wouda actually I'm in a learning stage and trying to help others, so they don't get stuck in such basic problems. – Akshay Sahai Jan 06 '16 at 22:42
  • That is quite commendable, don't get me wrong. But this particular question seems like it was already well-covered by the other answers, so it might be more productive to answer questions that do not yet have good anwers! – Nelewout Jan 06 '16 at 22:51
  • 2
    If 'a' is a string, int(a) throws an exception and the 'else' branch never gets called. Tested in python 2 & 3. – nevelis Sep 13 '16 at 20:26
0
while True:
    b1=input('Type a number:')
    try:
        a1=int(b1)
    except ValueError:
        print ('"%(a1)s" is not a number. Try again.' %{'a1':b1})       
    else:
        print ('You typed "{}".'.format(a1))
        break

This makes a loop to check whether input is an integer or not, result would look like below:

>>> %Run 1.1.py
Type a number:d
"d" is not a number. Try again.
Type a number:
>>> %Run 1.1.py
Type a number:4
You typed 4.
>>> 
0

If you wanted to evaluate floats, and you wanted to accept NaNs as input but not other strings like 'abc', you could do the following:

def isnumber(x):
    import numpy
    try:
        return type(numpy.float(x)) == float
    except ValueError:
        return False
ryanjdillon
  • 15,701
  • 7
  • 81
  • 102
0

try this! it worked for me even if I input negative numbers.

  def length(s):
    return len(s)

   s = input("Enter the String: ")
    try:
        if (type(int(s)))==int :
            print("You input an integer")

    except ValueError:      
        print("it is a string with length " + str(length(s)))   
0

This will work:

print(user_input.isnumeric())

This checks if the string has only numbers in it and has at least a length of 1. However, if you try isnumeric with a string with a negative number in it, isnumeric will return False.

Now this is a solution that works for both negative and positive numbers

try:
    user_input = int(user_input)
except ValueError:
    process_non_numeric_user_input()  # user_input is not a numeric string!
else:
    process_user_input()
Bgil Midol
  • 814
  • 4
  • 23
0

You Can Type:

user_input = input("Enter something: ")

if type(user_input) == int:
    print(user_input, "Is a number")
else:
    print("Not a number")
  
try:
    val = int(user_input)
except ValueError:
    print("That's not an int!")
0

Checking for Decimal type:

import decimal
isinstance(x, decimal.Decimal)
AidinZadeh
  • 648
  • 1
  • 7
  • 15
0

I think not done simple thing in one line is not pythonnic.

A version without try..except, use regex match:

code:

import re

if re.match('[-+]?\d+$', the_str):
  # is integer

test:

>>> import re
>>> def test(s): return bool(re.match('[-+]?\d+$', s))

>>> test('0')
True
>>> test('1')
True
>>> test('-1')
True

>>> test('-0')
True
>>> test('+0')
True
>>> test('+1')
True


>>> test('-1-1')
False
>>> test('+1+1')
False


yurenchen
  • 1,304
  • 15
  • 13
-2

Based on inspiration from answer. I defined a function as below. Looks like its working fine. Please let me know if you find any issue

def isanumber(inp):
    try:
        val = int(inp)
        return True
    except ValueError:
        try:
            val = float(inp)
            return True
        except ValueError:
            return False
-3
a=10

isinstance(a,int)  #True

b='abc'

isinstance(b,int)  #False
ryanjdillon
  • 15,701
  • 7
  • 81
  • 102
sachkh
  • 13