Python: while 后跟 elif

Python: while followed by elif

我认为 else ifelif 在逻辑上是相同的。

但是当我在 while 之后尝试 elif 时,出现语法错误。

然而,elsewhile 之后是可以的,如下所示(参见注释 A 和 B):

MENU_COMMANDS = {
'goal': 'the objective of the game is .... ',
'close': 'exit menu',
'menu': 'show all menu commands',
'quit': 'quit game' }

GAME_KEYBOARD = {
'1': 1,
'2': 2 }

def turn1():
key = input("Player 1, make your move")  # == 'goal'

while key in MENU_COMMANDS:
    menu(key)
    key = input("after exiting the menu, make your move")
else:  # why not 'elif' ?    COMMENT A
    if key not in GAME_KEYBOARD:
        print("invalid move")
        return False

# elif key not in GAME_KEYBOARD:  # why won't this work? :(    COMMENT B
#     print("invalid move")
#     return False

这是执行此逻辑的唯一方法,还是有更好的方法?

谢谢!

if a:
    do something
elif b:
    do something
elif c:
    do something 
else:
    ouch

相同
if a:
    do this
if (not a) and b:
    do that
if (not a) and (not b) and c:
    do these
if (not a) and (not b) and (not c):
    no

elif: ... 等同于 if 块上下文中的 else: if: ...,但 while 块中的 else 具有完全不同的含义来自 if 块中的 else,因此即使它们由相同的关键字表示,两者也不可互换。

无论如何,此代码块中的 else 是不必要的:

while key in MENU_COMMANDS:
    menu(key)
    key = input("after exiting the menu, make your move")
else:  # why not 'elif' ?    COMMENT A
    if key not in GAME_KEYBOARD:
        print("invalid move")
        return False

由于您从未 break 您的 while,因此在任何情况下您都不会结束循环并且 不会 输入 else .因此,您可以删除 else 并且它的行为应该相同:

while key in MENU_COMMANDS:
    menu(key)
    key = input("after exiting the menu, make your move")

if key not in GAME_KEYBOARD:
    print("invalid move")
    return False

对于循环控制,else 是与标准条件语句相比的特例。

When used with a loop, the else clause has more in common with the else clause of a try statement than it does with that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs.

https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

>>> c = 0
>>> while c < 10:
...    break
... else:
...    print("caught a break")
...
>>> while c < 10:
...    c+=2
... else:
...    print("no break")
...
no break