我認為else if并且elif在邏輯上是相同的。
但是當我嘗試elif之后while,我得到一個語法錯誤。
但是,else之后就可以了while,如下所示(參見注釋 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
這是執行此邏輯的唯一方法,還是有更好的方法?
謝謝!
uj5u.com熱心網友回復:
elif: ...相當于else: if: ...在塊的背景關系中if,但是塊中else的while塊與塊中的含義完全不同,因此即使它們由相同的關鍵字表示,兩者也不能互換。elseif
無論如何,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
uj5u.com熱心網友回復:
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
uj5u.com熱心網友回復:
對于回圈控制,else是一種特殊情況與標準條件陳述句。
當與回圈一起使用時,else 子句與 try 陳述句的 else 子句的共同點比與 if 陳述句的共同點要多:try 陳述句的 else 子句在沒有例外發生時運行,回圈的 else 子句在沒有中斷時運行發生。
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/427565.html
上一篇:Pythonif...in...陳述句。檢查單詞中的元音
下一篇:重復ifelse塊
