我已经制作了一个程序,但是如果用户输入不是二进制格式,我想添加一个例外。我已经尝试了很多次添加例外,但似乎无法让它工作。下面是程序代码。如果有人可以提供帮助,我将不胜感激。
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)