【问题标题】:How can I check input is integer, while using FOR for RAW_INPUT ..in Python?如何在 Python 中使用 FOR 为 RAW_INPUT .. 时检查输入是否为整数?
【发布时间】:2015-04-23 10:38:19
【问题描述】:

我有一个任务

打印您输入的列表中的最小值。首次输入的值 定义列表的长度。每个下一个值都应该放在 一一列举。使用运算符 for

n 之前定义,通过输入和start_n = 1

def list2_func():     
    global list2
    list2 = []
    for i in xrange(start_n, n + 1):
        list2.append(raw_input('Enter the %s number: ' % i))
        list2_check()
def list2_check():
    global start_n
    try:
        value = int(list2[-1])
    except ValueError:
        print "Please use only 0-9 keys. Re enter %s number" % len(list2)
        start_n = len(list2)
        list2_func()
    else: 
        start_n = start_n + 1

每次我输入任何未通过 try 的键时,它都会再次要求相同的值 - 这很棒。但是当我输入我的最后一个值(例如n = 4,所以第 4 个值)时,程序要求我再次输入。最后我得到了2*n - 1 的值——这不是我想要的。

您能否建议我使用其他方法来检查输入的值是否为数字?或者指出我代码中的错误!

我使用的是 python 2.7。

【问题讨论】:

标签: python list python-2.7 for-loop try-catch


【解决方案1】:

您的代码中可能存在错误。如果检查失败,您将多次附加该数字。请尝试以下代码,以确保您将单个有效值附加到列表中。

def get_value(i):
    while True:
        number = raw_input('Enter the %s number: ' % i)
        try:
            value = int(number)
        except:
            continue
        return value

def list2_func():
    list2 = []
    for i in xrange(start_n, n + 1):
        number = get_value(i)
        list2.append(number)

【讨论】:

  • 这个解决方案的两个主要问题是不必要的递归和裸 except 子句。
  • @Nsh 删除了递归的使用,但你能帮我删除 except 子句,因为你说它在这种情况下看起来很裸露吗?
【解决方案2】:

你不需要使用 list2_check 函数:

def list2_func():     
        list2 = []
        i=start_n
        while i<n+1:
            try:
                list2.append(int(raw_input('Enter the %s number: ' % i)))
                i+=1
            except ValueError:
                print "Please use only 0-9 keys. Re enter %s number" % len(list2)
        return list2

我还删除了您的全局变量,因为最好使用返回而不是使用全局变量。 (如果您尝试使用另一个具有相同名称的变量,它们可能会导致问题)

【讨论】:

  • 谢谢!这也有效,但我必须按任务使用 FOR 运算符:)
【解决方案3】:

刚刚玩了一下代码,发现了问题。程序正在完成第一个 FOR 循环并为每个未通过 try 测试的值启动新的 for 循环。

def list2_func():
    global list2
    list2 = []
    for i in xrange(1, n+1):
        list2.append(raw_input('Enter the %s number: ' % i))
        list2_check()
def list2_check():
    try:
        value = int(list2[-1])
    except ValueError:
        list2[-1]= raw_input("Please, use only 0-9 keys" % len(list2))
        list2_check()
    else:
        pass

现在它只是要求替换错误的值,而不是再次启动 for 循环 :)

【讨论】:

    【解决方案4】:

    这是因为你有一个递归函数。每个函数调用另一个。 另外,strart_n 在每个循环中都会被修改(去掉 try 的 else 情况)。

    【讨论】:

      【解决方案5】:

      您的问题在于使用的逻辑:您添加了错误的输入值(通过 list2.append),然后检查列表,如果值错误,则永远不要删除最后输入的值。 所以,如果你想保留你的代码,你只需要在引发 ValueError 时删除列表中的最后一项。

      但是,您的代码还有许多其他问题需要解决: 你使用递归,你的程序很容易崩溃:只输入错误的值:每次,你在“list2_func”中对“list2_func”进行新的调用。所以我们有 5 个连续的错误值:

      call to list2_func:
          call to list2_func:
              call to list2_func:
                  call to list2_func:
                      call to list2_func:
      

      当然,当达到最大递归时,python 会崩溃:)

      另一个问题是全局变量的使用。这不好。仅当您确实需要全局变量时才这样做。

      这是您练习中现有的众多解决方案之一:

      def get_list():
          """
          Returns an user's entered list.
          First entered value defines the length of the list. 
          Each next value should be placed in list one by one. 
          """
          wanted_length = None
          my_list = []
          while wanted_length < 1:
              try:
                  wanted_length = int(raw_input('Please enter the wanted length of the list (int > 0) : '))
              except ValueError:
                  pass
          i = 1
          while i <= wanted_length:
              try:
                  my_list.append(int(raw_input('Please enther the number %d (int only) : ' % i)))
              except ValueError:
                  pass
              else:
                  i += 1
          return my_list
      
      def print_min_with_for(l):
          """
          Prints the minimal value from list you entered using operator `for`.
          """
          if not l:
              print 'List is empty'
              return
          min_value = None
          for i in l:
              if min_value is None or i < min_value:
                  min_value = i
          print 'min value in the list is : %d' % min_value
      
      my_list = get_list()
      print 'Printed min value in the list should be : %d' % min(my_list)
      print_min_with_for(my_list)
      

      欢迎来到 python BTW ;-)

      【讨论】:

        猜你喜欢
        • 2018-05-19
        • 1970-01-01
        • 2013-10-26
        • 2016-05-19
        • 2012-09-23
        相关资源
        最近更新 更多