Skip to main content
 首页 » 编程设计

python之while 语句和表达式

2025年05月04日27linjiqin

while 循环语句只要表达式为真就会执行。

在第 10 次之后,pop() 抛出一个 IndexError,因为列表中有 10 个元素。但是,下面的代码执行得很好,没有任何错误。为什么会这样?

a = [x*x for x in range(10)] 
while a.pop(): 
    print("elements in the list") 

这可能是一个非常基本的问题,但我正在尝试熟悉 Python。

请您参考如下方法:

After the 10th time, the pop() throws an IndexError back because there are 10 elements in the list.

不,代码从不尝试在第 10 个之后执行任何 pop,因为第 10 个 pop 返回 0。 0 在 bool 上下文中被视为 false,因此循环在该点终止。