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