piglei / one-python-craftsman

来自一位 Pythonista 的编程经验分享,内容涵盖编码技巧、最佳实践与思维模式等方面。

Home Page:https://www.piglei.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

关于「使用 try/while/for 中 else 分支」

cdpath opened this issue · comments

while ... else 和 for ... else 相当的反直觉,引用 Effective Python 中的例子(加了一些注释):

# 看上去 else 是「之前」没有运行才会运行的,实际上之前 for loop 完成之后还是运行了 else
for i in range(3):
  print(i)
else:
  print("ELSE!")      # 可及


# 看上去 for loop 退出了,应该运行 else 了,实际上 else 会被跳过
for i in range(3):
  print(i)
  if i == 1:
    break       # 注意这里的 break
else:
  print("ELSE!")      # 不可及
  

# for loop 是空的时候 直接执行 else
for i in []:
  print(i)
else:
  print("ELSE!")       # 可及


# while 初始条件是 False 时直接执行 else
while False:
    print("ok")
else:
    print("ELSE")      # 可及


a = iter([None, 1, 2, 3, None, 5, 6])
while next(a):
    print('hi')
else:
    print("ELSE")     # 可及

这里也有一些讨论:https://mail.python.org/pipermail/python-ideas/2009-October/006155.html

感谢提出这个问题。确实,这个 else 关键字被大家诟病已久,假如当初没使用 else,而是用了其他关键字,这些逻辑确实会好理解一些:

  • for/while 里的 "else" 也许应该被叫做 ”nobreak“
  • try 里的 "else" 也许应该被叫做 "then"

我在重写这部分内容会增加详细说明。