Skip to main content
 首页 » 编程设计

Python 在遍历列表时找不到值

2025年05月04日9qlqwjy

我有一个 while 循环,它遍历一个列表,试图找到数字 1。我有下面的代码,它“几乎”遍历了所有列表,但它没有找到值 1 的索引

numbers = [24, 10, 92, 28, 71, 1, 80, 70] 
counter = 0 
number_to_find = 1 
 
def my_loop(): 
    global counter 
    while counter > 6: #Also not sure while 7 doesn't work, says out of range? 
        if numbers[counter] == number_to_find: 
            print "Number found at position", counter  
     
    else: 
        print "Counter not found in position" , counter 
        counter = counter + 1 
        my_loop() 
 
 
print my_loop() 

请您参考如下方法:

这是一段非常困惑的代码。

  1. 您打印 输出,但该函数不返回任何内容。 (它也打印东西,但不返回任何东西。)
  2. 该函数有一个while 循环,并且还对自身进行递归。 (在某些情况下这是合适的,但这不是其中之一。)
  3. counter 最初为 0,但您的第一个检查是 counter > 6。 0 不大于 6。 (这在技术上并没有错,但非常令人困惑。)
  4. 值 1 位于索引 5。为什么要查找 6?
  5. 一旦达到所需的索引,就不会终止循环。