且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查输入是否是Python中的数字?

更新时间:2022-02-18 07:28:39

如果 int()调用成功,十进制 已经一个数字。您只能在字符串上调用 .isdigit()(正确的名称):

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)

另一种方法是使用异常处理;如果抛出 ValueError ,则输入不是数字:

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:]

而不是使用 bin()函数并删除起始 0b ,您还可以使用 format()函数,使用'b'格式,将整数格式化为二进制字符串,不带前导文本:

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'

format()函数可以轻松添加前导零:

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

>>> format(10, '08b')
'00001010'