首页 > 解决方案 > Python oneliner if 条件与多个语句用逗号和分号分隔

问题描述

a = True

if a : print('msg1'), print('msg2');
# msg1 and msg2 are printed

if a : print('msg1'), print('msg2'), b = 1;
# if a : print('msg1'), print('msg2'), b = 1;
#       ^
# SyntaxError: can't assign to function call

if a : print('msg1'); print('msg2'); b = 1;
# msg1 and msg2 are printed and b is also assigned the value 1

if a : b = 1; c = 5; print(b), print(c)
# b and c are assigned values 1 and 5, and both are printed

第一个 if 语句与 2 个打印语句之间的逗号一起使用。
第三个 if 语句也适用于所有用分号分隔的语句。

逗号和分号组合的第二个 if 语句不再起作用。
第 4 个 if 语句,打印语句用逗号分隔,普通语句用分号隔开。

所以在我看来,虽然打印语句可以用逗号分隔,但普通语句不能。因此,最好在单行 if 语句中用分号分隔所有内容。

有人可以解释/确认这背后的逻辑吗?

标签: pythonif-statementone-liner

解决方案


当你这样做时a, bfunction(value), function(value)这与 有很大不同function(value); function(value)。逗号有效地创建了一个元组,而分号分隔语句。这就是为什么分配在分号示例中有效但在逗号示例中无效的原因:

# this is the form of the comma statement
print('a'), b = 1

# raises a syntax error

# this is what the semicolon statements look like
print('a')
b = 1

真正的解决办法:停止尝试将所有内容都写成单行。比较两个语句:

if a: b = 1; print('msg1'), print('msg2')

if a:
    b = 1
    print('msg1')
    print('msg2')

第二个更容易阅读并且不那么混乱。仅仅因为它适合一行并不能使它变得更好。


推荐阅读