繁体   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