在整数用户输入中打印消息而不是值错误?

2024-09-27 23:23:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个十进制到二进制的转换器,如下所示:

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,但我觉得这是一种懒惰和粗糙的方式。你知道吗

但是,我认为在用户输入行之后尝试添加的任何内容都将无法工作,因为程序将在到达该行之前终止,这是对的吗?你知道吗

还有其他建议吗?你知道吗


Tags: to用户in程序forifvalue二进制
2条回答

您需要使用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了解详细信息。根据doc,try语句的工作方式如下:

  • 首先,执行try子句(tryexcept关键字之间的语句)。你知道吗
  • 如果没有发生异常,则跳过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,而是使用字符串的^{}方法检查输入字符串是否是数字,如果不是,则跳过循环(使用^{}语句)。你知道吗

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)

相关问题 更多 >

    热门问题