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

前端 未结 1 469
庸人自扰
庸人自扰 2020-12-12 00:20

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

相关标签:
1条回答
  • 2020-12-12 01:21

    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'
    
    0 讨论(0)
提交回复
热议问题