【问题标题】:One-line if/else unexpected SyntaxError单行 if/else unexpected SyntaxError
【发布时间】:2023-01-05 08:05:44
【问题描述】:

Python 单行 if/else 语句应该可以在不引发 SyntaxError 的情况下运行,但它们会使用一些关键字。

pass if arg else pass的预期结果应该与print('') if arg else print('')类似。虽然它们看起来很相似,但一个会导致语法错误,而另一个则不会。为什么解释器允许以这种方式使用某些关键字而不是其他关键字?

def foo(arg):
    #raise BaseExecption if arg else raise BaseException
    #pass if arg else pass
    print('') if arg else print('')
    
foo(True)

注意:注释掉的代码行将产生 SyntaxError。

【问题讨论】:

  • Python 中没有单行 if/else 语句。如果您想要一个语句,请使用标准的多行 if/else。 x if y else z 是一个条件表达式。

标签: python


【解决方案1】:

我相信三元逻辑仅适用于变量赋值,例如:

x = 1 if True else 9

【讨论】:

    猜你喜欢
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多