【问题标题】:Try-Except ErrorCatchingTry-Except ErrorCatching
【发布时间】:2017-05-14 00:54:22
【问题描述】:

我试图强制用户在 python 中使用 try-except 输入一个数字,但它似乎没有效果。

while count>0:
    count=count - 1
    while (length != 8):
        GTIN=input("Please enter a product code ")
        length= len(str(GTIN))
        if length!= 8:
            print("That is not an eight digit number")
            count=count + 1
         while valid == False:
            try:
                GTIN/5
                valid = True
            except ValueError:
                 print("That is an invalid number")
                 count=count + 1

【问题讨论】:

    标签: python python-3.x exception-handling user-input


    【解决方案1】:

    实际上,如果用户输入例如一个字符串,"hello"/5 会产生一个TypeError,而不是ValueError,所以请抓住它

    【讨论】:

      【解决方案2】:

      您可以尝试将输入值设为 int int(value),如果无法转换,则会引发 ValueError

      这里有一个函数可以用一些 cmets 做你想做的事情:

      def get_product_code():
          value = ""
          while True:  # this will be escaped by the return
              # get input from user and strip any extra whitespace: " input  "
              value = raw_input("Please enter a product code ").strip()
              #if not value:            # escape from input if nothing is entered
              #    return None
              try:
                  int(value)           # test if value is a number
              except ValueError:       # raised if cannot convert to an int
                  print("Input value is not a number")
                  value = ""
              else:                    # an Exception was not raised
                  if len(value) == 8:  # looks like a valid product code!
                      return value
                  else:
                      print("Input is not an eight digit number")
      

      一旦定义,调用函数以获取用户的输入

      product_code = get_product_code()
      

      您还应该确保在您期待用户输入的任何时候排除和处理KeyboardInterrupt,因为他们可能会输入^C 或其他内容以使您的程序崩溃。

      product code = None  # prevent reference before assignment bugs
      try:
          product_code = get_product_code()  # get code from the user
      except KeyboardInterrupt:  # catch user attempts to quit
          print("^C\nInterrupted by user")
      
      if product_code:
          pass  # do whatever you want with your product code
      else:
          print("no product code available!")
          # perhaps exit here
      

      【讨论】:

      • 你怎么称呼这个?
      • 一旦定义,就像调用任何其他函数一样。 Here's a fairly good explanation of that process and usage
      • 啊,我现在明白了,但是我想在代码中使用它,而不是在 shell 中。我会看看我是否可以根据我的需要调整它,谢谢
      • 随时!这应该在 shell 和脚本文件中都有效。如果 SO 上的这个或另一个答案解决了您提出的问题,请将其标记为答案。
      猜你喜欢
      • 2019-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-19
      • 2011-04-25
      • 2011-09-29
      • 2019-09-28
      • 1970-01-01
      相关资源
      最近更新 更多