SyntaxError: 使用空块时if和elif需要缩进块

1 投票
1 回答
11046 浏览
提问于 2025-04-18 14:53

看起来我的代码有问题。当我在Python 3.3.3的环境中运行下面的模块时,出现了一个错误,提示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()

1 个回答

5

在每个 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 会退出函数(也就是退出循环),否则用户会一直被要求提供有效的输入。

撰写回答