如何在Python中检查输入是否为数字?
我有一个Python脚本,它将十进制数转换为二进制数,这显然使用了它们的输入 我想让脚本验证输入是一个数字,而不是任何其他将停止脚本的内容 我试过一个if/else语句,但我真的不知道该怎么做。我尝试了如何在Python中检查输入是否为数字?,python,if-statement,input,numbers,Python,If Statement,Input,Numbers,我有一个Python脚本,它将十进制数转换为二进制数,这显然使用了它们的输入 我想让脚本验证输入是一个数字,而不是任何其他将停止脚本的内容 我试过一个if/else语句,但我真的不知道该怎么做。我尝试了if decimal.isint():和if decimal.isalpha():,但当我输入字符串时,它们只会抛出错误 print("Welcome to the Decimal to Binary converter!") while True: print("Type a decim
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.")
如果没有if/else语句,代码工作正常并完成了它的工作。如果int()
调用成功,decimal
已经是一个数字。只能对字符串调用.isdigit()
(正确的名称):
decimal = input()
if decimal.isdigit():
decimal = int(decimal)
另一种方法是使用异常处理;如果抛出ValueError
,则输入不是数字:
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()
>>> format(10, 'b')
'1010'
format()
函数可以轻松添加前导零:
>>> format(10, '08b')
'00001010'
在Python2.x中,实际上不需要调用isdigit
,这将抛出error@elssar:这显然不是Python 2。在Python2中,在本例中使用raw\u input()
。是的,但我认为在回答中应该提到这一点。我匆忙中忘了提那一点:/