我已经制作了一个程序,但是如果用户输入不是二进制格式,我想添加一个异常(exception)。我试过很多次添加异常(exception),但我似乎无法让它工作。下面是程序代码。如果有人可以提供帮助,我将不胜感激。
import time
error=True
n=0
while n!=1:
print"***Welcome to the Bin2Dec Converter.***\n"
while error:
try:
bin2dec =raw_input("Please enter a binary number: ")
error=False
except NameError:
print"Enter a Binary number. Please try again.\n"
time.sleep(0.5)
except SyntaxError:
print"Enter a Binary number. Please try again.\n"
time.sleep(0.5)
#converts bin2dec
decnum = 0
for i in bin2dec:
decnum = decnum * 2 + int(i)
time.sleep(0.25)
print decnum, "<<This is your answer.\n" #prints output
最佳答案
最好请求原谅。尝试使用 int(value, 2)
将其转换为整数:
while True:
try:
decnum = int(raw_input("Please enter a binary number: "), 2)
except ValueError:
print "Enter a Binary number. Please try again.\n"
else:
break
print decnum
关于python - 如何检查输入是否为二进制格式(1 和 0)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18812047/