簡體   English   中英

SyntaxError:在將if和elif與空塊一起使用時,期望縮進的塊

[英]SyntaxError: expected an indented block when using if and elif with empty blocks

顯然我的代碼有問題。 當我使用Python 3.3.3 Shell運行以下模塊時,出現錯誤SyntaxError: expected an indented block 然后IDLE在第7行突出顯示elif

def user_input():
    print('[1]: ASCII to Binary')
    print('[2]: Binary to ASCII')
    user_input = input('Please choose [1] or [2]: ')
    if user_input == ('1', '[1]'):
        #
    elif user_input == ('2', '[2]'):
        #
    else:
        print('Please enter a valid input...')
        user_input()

每個ifelif塊中都必須有實際的代碼,不能僅使用注釋。

在以下情況下使用pass語句

if user_input == ('1', '[1]'):
    pass
elif user_input == ('2', '[2]'):
    pass
else:
    print('Please enter a valid input...')
    user_input()

另外,您實際上不能在函數中使用user_input作為局部變量名稱, 並且仍然能夠使用該名稱調用該函數。 局部變量遮蔽全局變量,因此在else:套件中的user_input()調用將引發TypeError因為它實際上是將由局部變量引用的字符串。 為本地變量使用其他名稱; choice將是一個不錯的選擇。

接下來,將字符串與元組進行比較,這兩種類型將永遠不相等in用於測試元組中是否存在與用戶輸入相等的字符串:

if choice in ('1', '[1]'):
    pass

如果您使用的集( {element1, element2, ...} )甚至更好,因為測試集后更快。

可以只反轉並合並測試,而根本不需要那些空塊:

choice = input('Please choose [1] or [2]: ')
if choice not in {'1', '[1]', '2', '[2]'}:
    print('Please enter a valid input...')
    user_input()

最后,使用循環(而不是遞歸)重復輸入錯誤的問題。 這樣一來,您就可以避免在不返回調用鏈上遞歸調用結果的情況下所犯的錯誤,並避免了遞歸限制(您不能無限期地返回函數,而您會驚訝地發現有多少用戶會嘗試使用該函數以了解他們可以繼續輸入錯誤選項的時間)。

while True循環確實會繼續下去:

def user_input():
    print('[1]: ASCII to Binary')
    print('[2]: Binary to ASCII')
    while True:
        choice = input('Please choose [1] or [2]: ')
        if choice in {'1', '[1]', '2', '[2]'}:
            return choice
        print('Please enter a valid input...')

return退出功能(因此退出循環),否則將永遠告知用戶提供有效輸入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM