我有一个十进制到二进制的转换器,如下所示:
print ("Welcome to August's decimal to binary converter.")
while True:
value = int(input("Please enter enter a positive integer to be converted to binary."))
invertedbinary = []
initialvalue = value
while value >= 1:
value = (value/2)
invertedbinary.append(value)
value = int(value)
for n,i in enumerate(invertedbinary):
if (round(i) == i):
invertedbinary[n]=0
else:
invertedbinary[n]=1
invertedbinary.reverse()
result = ''.join(str(e) for e in invertedbinary)
print ("Decimal Value:\t" , initialvalue)
print ("Binary Value:\t", result)
用户输入会立即声明为整数,因此除了输入数字以外的任何内容都会终止程序并返回ValueError
。我怎样才能使它打印一条消息而不是程序以ValueError
结束?你知道吗
我试着用我从二进制到十进制转换器中使用的方法:
for i in value:
if not (i in "1234567890"):
我很快就意识到这是行不通的,因为value
是整数而不是字符串。我想我可以将用户输入保留为默认字符串,然后再将其转换为int
,但我觉得这是一种懒惰和粗糙的方式。你知道吗
但是,我认为在用户输入行之后尝试添加的任何内容都将无法工作,因为程序将在到达该行之前终止,这是对的吗?你知道吗
还有其他建议吗?你知道吗
您需要使用
try/except
块来处理ValueError
异常。你的代码应该是这样的:如果用户输入任何不能转换成
int
的值,它将引发ValueError
异常,该异常将由except
块处理并打印您提到的消息。你知道吗阅读Python: Errors and Exceptions了解详细信息。根据doc,
try
语句的工作方式如下:try
子句(try
和except
关键字之间的语句)。你知道吗except
子句,并完成try
语句的执行。你知道吗try
子句期间发生异常,则跳过该子句的其余部分。然后,如果其类型匹配以except关键字命名的异常,则执行except子句,然后在try语句之后继续执行。你知道吗except
子句中指定的异常不匹配,则将其传递给外部try
语句;如果找不到处理程序,则该异常是未处理的异常,执行将停止,并显示如上所示的消息。你知道吗在这些情况下,我认为最具Pythonic效果的方法是将可能在try/catch(或try/except)中得到异常的行包装起来,如果得到
ValueError
异常,则显示适当的消息:另一个选项(但比处理异常慢得多)是,不立即转换为} 方法检查输入字符串是否是数字,如果不是,则跳过循环(使用^{} 语句)。你知道吗
int
,而是使用字符串的^{相关问题 更多 >
编程相关推荐