如何检查输入是否为 Python 中的数字? [英] How do I check if input is a number in Python?

查看:33
本文介绍了如何检查输入是否为 Python 中的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

print("欢迎使用十进制转二进制转换器!")而真:print("请输入要转换的十进制数:")十进制 = 整数(输入())如果十进制.isint():二进制 = bin(十进制)[2:]打印(二进制)别的:print("请输入一个数字.")

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

解决方案

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

decimal = input()如果decimal.isdigit():十进制 = 整数(十进制)

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

虽然为真:print("请输入要转换的十进制数:")尝试:十进制 = 整数(输入())除了值错误:print("请输入一个数字.")继续二进制 = bin(十进制)[2:]

您也可以使用 format() 函数,使用 'b' 格式,将整数格式化为二进制字符串, 没有前导文本:

<预><代码>>>>格式(10,'b')'1010'

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

<预><代码>>>>格式(10,'08b')'00001010'

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.

解决方案

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'

这篇关于如何检查输入是否为 Python 中的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆