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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20095244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:30:20  来源:igfitidea点击:

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

pythonif-statementinputnumbers

提问by RoyalSwish

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

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

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.

我试过 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.")

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

如果没有 if/else 语句,代码就可以正常工作并完成它的工作。

采纳答案by Martijn Pieters

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

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

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

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

另一种方法是使用异常处理;如果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:]

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:

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

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

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

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

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