How do I check if input is a number in Python?(如何检查输入是否是 Python 中的数字?)
问题描述
我有一个 Python 脚本,可以将十进制数转换为二进制数,这显然使用了他们的输入.
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.
我尝试了 if/else 语句,但我真的不知道该怎么做.我试过 if decimal.isint():
和 if decimal.isalpha():
但当我输入字符串时它们只会抛出错误.
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.")
没有 if/else 语句,代码可以正常工作并完成其工作.
Without the if/else statement, the code works just fine and does its job.
推荐答案
如果int()
调用成功,decimal
是已经数字.您只能在字符串上调用 .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'
这篇关于如何检查输入是否是 Python 中的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检查输入是否是 Python 中的数字?


基础教程推荐
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01