在整数用户输入中打印消息而不是 valuerror?
Printing message rather than valuerror in an integer user input?
我有一个十进制到二进制的转换器,如下所示:
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)
用户输入立即声明为整数,因此输入的数字以外的任何内容都会终止程序并且 returns a ValueError
。我怎样才能打印一条消息而不是程序以 ValueError
?
终止
我尝试采用我在二进制到十进制转换器中使用的方法:
for i in value:
if not (i in "1234567890"):
我很快意识到这是行不通的,因为 value
是一个整数而不是字符串。我在想我可以将用户输入保留在默认字符串,然后将其转换为 int
但我觉得这是懒惰和粗暴的方式。
但是,我是否认为我在用户输入行之后尝试添加的任何内容都不起作用,因为程序会在到达该行之前终止?
还有其他建议吗?
您需要使用 try/except
块处理 ValueError
异常。你的代码应该是这样的:
try:
value = int(input("Please enter enter a positive integer to be converted to binary."))
except ValueError:
print('Please enter a valid integer value')
continue # To skip the execution of further code within the `while` loop
如果用户输入任何无法转换为 int
的值,它将引发 ValueError
异常,该异常将由 except
块处理并打印消息你提到了。
阅读 Python: Errors and Exceptions 了解详细信息。根据文档,try
语句的工作方式如下:
- 首先,执行
try
子句(try
和except
关键字之间的语句)。
- 如果没有异常发生,则跳过
except
子句,try
语句执行完毕。
- 如果在
try
子句的执行过程中发生异常,则跳过该子句的其余部分。然后如果其类型匹配以except关键字命名的异常,则执行except子句,然后在try语句之后继续执行。
- 如果发生与
except
子句中命名的异常不匹配的异常,则将其传递给外部 try
语句;如果未找到处理程序,则为未处理的异常,执行将停止并显示如上所示的消息。
我认为在这些情况下,我认为最 Pythonic 的方法是将可能出现异常的行换行到 try/catch(或 try/except) 并在出现 ValueError
异常时显示正确的消息:
print ("Welcome to August's decimal to binary converter.")
while True:
try:
value = int(input("Please enter enter a positive integer to be converted to binary."))
except ValueError:
print("Please, enter a valid number")
# Now here, you could do a sys.exit(1), or return... The way this code currently
# works is that it will continue asking the user for numbers
continue
您有另一个选择(但比处理异常慢得多)是,不是立即转换为 int
,而是使用 str.isdigit()
method of the strings and skip the loop (using the continue
语句检查输入字符串是否为数字)如果不是。
while True:
value = input("Please enter enter a positive integer to be converted to binary.")
if not value.isdigit():
print("Please, enter a valid number")
continue
value = int(value)
我有一个十进制到二进制的转换器,如下所示:
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)
用户输入立即声明为整数,因此输入的数字以外的任何内容都会终止程序并且 returns a ValueError
。我怎样才能打印一条消息而不是程序以 ValueError
?
我尝试采用我在二进制到十进制转换器中使用的方法:
for i in value:
if not (i in "1234567890"):
我很快意识到这是行不通的,因为 value
是一个整数而不是字符串。我在想我可以将用户输入保留在默认字符串,然后将其转换为 int
但我觉得这是懒惰和粗暴的方式。
但是,我是否认为我在用户输入行之后尝试添加的任何内容都不起作用,因为程序会在到达该行之前终止?
还有其他建议吗?
您需要使用 try/except
块处理 ValueError
异常。你的代码应该是这样的:
try:
value = int(input("Please enter enter a positive integer to be converted to binary."))
except ValueError:
print('Please enter a valid integer value')
continue # To skip the execution of further code within the `while` loop
如果用户输入任何无法转换为 int
的值,它将引发 ValueError
异常,该异常将由 except
块处理并打印消息你提到了。
阅读 Python: Errors and Exceptions 了解详细信息。根据文档,try
语句的工作方式如下:
- 首先,执行
try
子句(try
和except
关键字之间的语句)。 - 如果没有异常发生,则跳过
except
子句,try
语句执行完毕。 - 如果在
try
子句的执行过程中发生异常,则跳过该子句的其余部分。然后如果其类型匹配以except关键字命名的异常,则执行except子句,然后在try语句之后继续执行。 - 如果发生与
except
子句中命名的异常不匹配的异常,则将其传递给外部try
语句;如果未找到处理程序,则为未处理的异常,执行将停止并显示如上所示的消息。
我认为在这些情况下,我认为最 Pythonic 的方法是将可能出现异常的行换行到 try/catch(或 try/except) 并在出现 ValueError
异常时显示正确的消息:
print ("Welcome to August's decimal to binary converter.")
while True:
try:
value = int(input("Please enter enter a positive integer to be converted to binary."))
except ValueError:
print("Please, enter a valid number")
# Now here, you could do a sys.exit(1), or return... The way this code currently
# works is that it will continue asking the user for numbers
continue
您有另一个选择(但比处理异常慢得多)是,不是立即转换为 int
,而是使用 str.isdigit()
method of the strings and skip the loop (using the continue
语句检查输入字符串是否为数字)如果不是。
while True:
value = input("Please enter enter a positive integer to be converted to binary.")
if not value.isdigit():
print("Please, enter a valid number")
continue
value = int(value)