How do I check if input is a number in Python?

30,735

If the int() call succeeded, decimal is already a number. You can only call .isdigit() (the correct name) on a string:

decimal = input()
if decimal.isdigit():
    decimal = int(decimal)

The alternative is to use exception handling; if a ValueError is thrown, the input was not a number:

while True:
    print("Type a decimal number you wish to convert:")
    try:
        decimal = int(input())
    except ValueError:
        print("Please enter a number.")
        continue

    binary = bin(decimal)[2:]

Instead of using the bin() function and removing the starting 0b, you could also use the format() function, using the 'b' format, to format an integer as a binary string, without the leading text:

>>> format(10, 'b')
'1010'

The format() function makes it easy to add leading zeros:

>>> format(10, '08b')
'00001010'
Share:
30,735
RoyalSwish
Author by

RoyalSwish

Studying Computing and Information Systems at University and working for the Systems Development team at a college. Adept user of HTML5, CSS3, SQL Server; intermediate user of JavaScript and PHP; novice at C#, ASP.NET; complete noob at everything else.

Updated on June 26, 2020

Comments

  • RoyalSwish
    RoyalSwish almost 4 years

    I have a Python script which converts a decimal number into a binary one and this obviously uses their input.

    I would like to have the script validate that the input is a number and not anything else which will stop the script.

    I have tried an if/else statement but I don't really know how to go about it. I have tried if decimal.isint(): and if decimal.isalpha(): but they just throw up errors when I enter a string.

    print("Welcome to the Decimal to Binary converter!")
    while True:
        print("Type a decimal number you wish to convert:")
        decimal = int(input())
        if decimal.isint():
            binary = bin(decimal)[2:]
            print(binary)
        else:
            print("Please enter a number.")
    

    Without the if/else statement, the code works just fine and does its job.

  • elssar
    elssar over 10 years
    In Python 2.x, you wouldn't need to call isdigit, infact, that would throw an error
  • Martijn Pieters
    Martijn Pieters over 10 years
    @elssar: this is clearly not Python 2. In Python 2, you'd use raw_input() in this case.
  • elssar
    elssar over 10 years
    well yes, but I thought it should be worth mentioning that in the answer. In my haste I forgot to mention that bit :/