简体   繁体   English

单行 if/else unexpected SyntaxError

[英]One-line if/else unexpected SyntaxError

Python one-line if/else statements should function without raising a SyntaxError, but with some keywords they do. Python 单行 if/else 语句应该 function 不会引发 SyntaxError,但它们会引发一些关键字。

The expected results of pass if arg else pass should be similar to print('') if arg else print('') . pass if arg else pass的预期结果应该类似于print('') if arg else print('') While they appear similar, one results in a syntax error and the other does not.虽然它们看起来很相似,但一个会导致语法错误,而另一个则不会。 Why does the interpreter permit some keywords to be used this way and not others?为什么解释器允许以这种方式使用某些关键字而不是其他关键字?

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

Note: The commented out lines of code will generate a SyntaxError.注意:注释掉的代码行将产生 SyntaxError。

pass is a statement (specifically a "simple statement"); pass是一个语句(特别是“简单语句”); it isn't an expression.这不是一个表达。 That's a problem because conditional expressions ("ternaries") only work on expressions.这是一个问题,因为条件表达式(“三元组”)仅适用于表达式。 Here's their entry in the Python grammar:这是他们在 Python 语法中的条目:

disjunction 'if' disjunction 'else' expression

All parts there are expressions besides the keywords.除了关键字之外,所有部分都有表达式。

This isn't really a problem through since you're abusing conditional expressions in the first place.这并不是真正的问题,因为您首先滥用了条件表达式。 Instead, use a full if -statement.相反,使用完整的if语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM