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

Roy*_*ish 2 python if-statement numbers input

我有一个Python脚本,它将十进制数转换为二进制数,这显然使用了他们的输入.

我想让脚本验证输入是一个数字,而不是任何会停止脚本的东西.

我尝试过if/else语句,但我真的不知道如何去做.我曾尝试if decimal.isint():if decimal.isalpha():,但是当我输入一个字符串,他们只是扔了错误.

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.")
Run Code Online (Sandbox Code Playgroud)

如果没有if/else语句,代码就可以正常运行并完成其工作.

Mar*_*ers 7

如果int()呼叫成功,decimal已经是一个号码.您只能.isdigit()在字符串上调用(正确的名称):

decimal = input()
if decimal.isdigit():
    decimal = int(decimal)
Run Code Online (Sandbox Code Playgroud)

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

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:]
Run Code Online (Sandbox Code Playgroud)

而不是使用的bin()功能和消除出发0b,你也可以使用format()功能,使用'b'格式来格式化一个整数作为二进制字符串,没有领先的文字:

>>> format(10, 'b')
'1010'
Run Code Online (Sandbox Code Playgroud)

format()功能可以轻松添加前导零:

>>> format(10, '08b')
'00001010'
Run Code Online (Sandbox Code Playgroud)

  • @elssar:这显然不是Python 2.在Python 2中,在这种情况下你会使用`raw_input()`. (2认同)