Home > Back-end >  Python: while followed by elif
Python: while followed by elif

Time:02-14

I thought else if and elif are logically identical.

But when I try elif after while, I get a syntax error.

However, else is OK after while, as shown here (see comments 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

Is this the only way to execute this logic, or is there a better one?

Thank you!

CodePudding user response:

elif: ... is equivalent to else: if: ... in the context of an if block, but the else in a while block has an entirely different meaning from the else in an if block, so the two aren't interchangeable even though they're represented by the same keyword.

The else in this code block is unnecessary anyway:

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

Since you never break your while, there's no circumstance under which you'd end the loop and not enter the else. Hence you can just remove the else and it should behave the same:

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

CodePudding user response:

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

is the same as

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

CodePudding user response:

For using elif in Python you must specify a condition along with it. Elif conditional statement can only be used after if conditional statement.

CodePudding user response:

For loop control, else is a special case vs standard conditional statement.

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
  • Related