Python while循环-相似代码中的差异

我刚刚学习了Python中的while循环,并希望了解为什么以下两个代码具有不同的输出。由于while循环在squares元素不为“ orange”时在迭代时停止,因此我认为两者的输出应为['orange','orange']。您能解释一下两者之间的区别吗?

# code1
squares = ['orange', 'orange', 'red']
new_squares = []

i=0
square=squares[0]

while(square=='orange'):
    new_squares.append(square)
    square=squares[i]
    i = i + 1
print(new_squares)


# code2
squares = ['orange', 'orange', 'red']
new_squares = []

i = 0
while(squares[i] == 'orange'):
    new_squares.append(squares[i])
    i = i + 1
print (new_squares)
评论
  • 鸣人
    鸣人 回复

    第一个while有一个额外的“ square = squares [i]”。 如果您这样更改它,您将得到相同的结果:

    # code1
    squares = ['orange', 'orange', 'red']
    new_squares = []
    
    i=0
    square=squares[0]
    
    while(square=='orange'):
        square=squares[i]
        new_squares.append(square)
        i = i + 1
    print(new_squares)
    
    
    # code2
    squares = ['orange', 'orange', 'red']
    new_squares = []
    
    i = 0
    while(squares[i] == 'orange'):
        new_squares.append(squares[i])
        i = i + 1
    print (new_squares)