三元if-else语句中的语法错误 [英] Syntax error in ternary if-else statement

查看:53
本文介绍了三元if-else语句中的语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以像这样使用if-else:

We can use if-else like this:

statement if condition else statement

但是这里有些问题,我不明白为什么.

but there are some problems here and I can't understand why.

  1. 如果我运行 count + = 1,如果为true,否则l = [] (已经定义了count),则会引发错误:

  1. If I run count += 1 if True else l = [] (count is defined already), then it raises an error:

 File "<ipython-input-5-d65dfb3e9f1c>", line 1
 count += 1 if True else l = []
                           ^
 SyntaxError: invalid syntax

我们不能再赋一个值吗?

Can we not assign a value after else?

当我运行 count + = 1时,如果为False,否则l.append(count + 1)(注意:count = 0,l = []),将引发错误:

When I run count += 1 if False else l.append(count+1) (note: count = 0, l = []), an error will be raised:

 TypeError    Traceback (most recent call last)
 <ipython-input-38-84cb28b02a03> in <module>()
 ----> 1 count += 1 if False else l.append(count+1)

 TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'

,l的结果是 [1] .

使用相同的条件,如果我使用if-else块,则没有错误.

Using the same conditions, if I use an if-else block, there are no errors.

您能解释一下区别吗?

推荐答案

条件表达式" A,如果C否则B 不是if/else语句

The "conditional expression" A if C else B is not a one-line version of the if/else statement if C: A; else: B, but something entirely different. The first will evaluate the expressions A or B and then return the result, whereas the latter will just execute either of the statements A or B.

更清楚地,如果为true,则 count + = 1,否则为l = [] not (计数+ = 1),如果为true,否则为(l = []),但 count + =(如果为True,则为1,否则l = []),但 l = [] 不是表达式,因此语法错误.

More clearly, count += 1 if True else l = [] is not (count += 1) if True else (l = []), but count += (1 if True else l = []), but l = [] is not an expression, hence the syntax error.

同样,如果为False,则 count + = 1,否则l.append(count + 1)不是,如果为False,则(count + = 1),否则为(l.append(count + 1)),但 count + =(如果为False,则为1,否则l.append(count + 1)).从语法上讲,这没关系,但是 append 返回 None ,该值不能添加到 count 中,因此无法添加TypeError.

Likewise, count += 1 if False else l.append(count+1) is not (count += 1) if False else (l.append(count+1)) but count += (1 if False else l.append(count+1)). Syntactically, this is okay, but append returns None, which can not be added to count, hence the TypeError.

这篇关于三元if-else语句中的语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆