相关疑难解决方法(0)

关于Python while语句的Else子句

我注意到以下代码在Python中是合法的.我的问题是为什么?有具体原因吗?

n = 5
while n != 0:
    print n
    n -= 1
else:
    print "what the..."
Run Code Online (Sandbox Code Playgroud)

python syntax if-statement while-loop

293
推荐指数
7
解决办法
17万
查看次数

为什么else/while语句中的else表现不同而不是if/try语句?

我最近偶然发现了Python在不同复合语句中处理else子句的方式似乎不一致.由于Python设计得很好,我确信有一个很好的解释,但我想不到它.

考虑以下:

if condition:
   do_something()
else:
   do_something_else()
Run Code Online (Sandbox Code Playgroud)

这里do_something_else()只有if condition是假的才会执行.

同样地,在

try:
   do_something()
except someException:
   pass:
else:
   do_something_else()
finally:
   cleanup()
Run Code Online (Sandbox Code Playgroud)

do_something_else() 仅在未发生异常时执行.

但是在for或while循环中,总是执行else子句,无论是否for/while block已经执行了内容.

for i in some_iterator:
   print(i)
else:
   print("Iterator is empty!")
Run Code Online (Sandbox Code Playgroud)

将永远打印"Iterator is empty!",无论我是说some_iterator = []还是some_iterator = [1,2,3].while-else子句中的行为相同.在我看来,在这些情况下else表现得更像finally.我在俯瞰什么?

python flow-control

6
推荐指数
2
解决办法
377
查看次数

标签 统计

python ×2

flow-control ×1

if-statement ×1

syntax ×1

while-loop ×1