【问题标题】:Printing message rather than valuerror in an integer user input?在整数用户输入中打印消息而不是 valueerror?
【发布时间】:2017-03-06 13:47:27
【问题描述】:

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

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,但我觉得这是一种懒惰而粗暴的方式。

但是,我是否认为我在用户输入行之后尝试添加的任何内容都不起作用,因为程序将在到达该行之前终止?

还有其他建议吗?

【问题讨论】:

    标签: python binary converter


    【解决方案1】:

    您需要使用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 子句(tryexcept 关键字之间的语句)。
    • 如果未发生异常,则跳过except 子句并完成try 语句的执行。
    • 如果在执行try 子句期间发生异常,则跳过该子句的其余部分。然后如果它的类型匹配以except关键字命名的异常,则执行except子句,然后在try语句之后继续执行。
    • 如果发生与except 子句中指定的异常不匹配的异常,则将其传递给外部try 语句;如果未找到处理程序,则为未处理的异常,执行将停止并显示如上所示的消息。

    【讨论】:

      【解决方案2】:

      在这些情况下,我认为最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
      

      您拥有的另一个选项(但比处理异常慢得多)是,使用字符串的str.isdigit() 方法检查输入字符串是否为数字并跳过循环,而不是立即转换为int(如果不是,则使用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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-10
        • 2016-05-30
        • 1970-01-01
        • 2020-08-09
        • 2021-11-27
        相关资源
        最近更新 更多